How do I alter XML with PowerShell/XPath and save the document? How do I alter XML with PowerShell/XPath and save the document? powershell powershell

How do I alter XML with PowerShell/XPath and save the document?


If you're using PowerShell 2.0 you can use the new Select-Xml cmdlet to select xml based on an XPath expression e.g.:

$xml = '<doc><books><book title="foo"/></books></doc>'$xml | Select-Xml '//book'Node    Path          Pattern----    ----          -------book    InputStream   //book

To remove nodes:

PS> $xml =[xml]'<doc><books><book title="foo"/><book title="bar"/></books></doc>'PS> $xml | Select-Xml -XPath '//book' |         Foreach {$_.Node.ParentNode.RemoveChild($_.Node)}title-----foobarPS> $xml.OuterXml<doc><books></books></doc>

Then to save to file:

$xml.Save("$pwd\foo.xml")Get-Content foo.xml<doc>  <books>  </books></doc>


Load Linq Xml assemblies:

[System.Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq")[System.Reflection.Assembly]::LoadWithPartialName("System.Xml.XPath")

Load your xml (Note, you can use ::Load("file") instead of ::Parse(...) to load from file:

$xml = [System.Xml.Linq.XDocument]::Parse("<root> <row>Hey</row> <row>you</row> </root>")

Modify (in this case Remove the first row:

[System.Xml.XPath.Extensions]::XPathSelectElement($xml, "//row").Remove()

Save to file:

$xml.Save("MyXml.xml")

Using System.Xml (instead of System.Xml.Linq):

$doc = new-object "System.Xml.XmlDocument"$doc.Load("MyXml_int.xml")$node = $doc.SelectSingleNode("//row");$node.ParentNode.RemoveChild($node)$doc.Save("MyXml_out.xml")