2

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?

1 Answer 1

7

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Nowhere else did I find such a concise correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.