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

PowerShellMicrosoft TechnologiesSoftware & Coding

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.

https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)

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
$xml.Save('C:\Temp\SampleXML.xml')

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)
$xml.SelectNodes("//book")
$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.

raja
Published on 01-Mar-2021 09:59:03
Advertisements