I need to use Powershell to extract a node (and children) from a larger XML document and create a new standalone XML document containing only the extracted XML node (and children); then I need to save this new extracted XML in a file. The top-level XML node being extracted has attributes. It appears that I will have to set the new XML object's XMLDocument value to do this, but XMLDocument is a read-only property. Can anyone help?
The crux is to use the XmlDocument.ImportNode()
method e.g.:
$xml1 = [xml](Get-Content foo.xml)
# find the node you want to extract
$node = $xml1.Foo.Bar
$xml2 = New-Object System.Xml.XmlDocument
$newNode = $xml2.ImportNode($node, $true)
$xml2.AppendChild($newNode)
$xml2.Save("bar.xml")