How to delete the specific node from the XML file using PowerShell?

To delete the specific XML node from the PowerShell, we can use the RemoveChild() method of the XML.

For example, We have a sample XML file from Microsoft.

We have saved the above file into C:\Temp\SampleXml.XML and we need to delete the book node with attribute ‘bk102’ and for that, we will use the XPath method of the XML.

Below commands will first search the XML book node with the book attribute ‘bk102’ and then we will delete it.

$xml = [xml](Get-Content C:\Temp\SampleXML.xml)
$node = $xml.SelectSingleNode("//book[@id='bk102']")
$node.ParentNode.RemoveChild($node) | Out-Null

If you want to delete all the nodes which have the name “Book”, we can use the below commands.

$xml = [xml](Get-Content C:\Temp\SampleXML.xml)
$nodes = $xml.SelectNodes("//book")
foreach($node in $nodes){$node.ParentNode.RemoveChild($node)}

In the above example, SelectNodes(‘//book’) method will select all nodes having the name Book and then deletes them.