Home > Blockchain >  Get XML node value into a variable as separate xml
Get XML node value into a variable as separate xml

Time:09-03

Would like to know, how to get content of an XML node as a full XML document in powershell. The structure is following:

<root>
    <apphdr></apphdr>
    <document></document>
</root>

I need all the contents for 'document' tags including the tags. Can`t wrap my mind around it on how to get it as separate xml instance.

CodePudding user response:

Using XPath is an easy way:

$xml = [xml]@"
<root>
    <apphdr></apphdr>
    <document></document>
</root>
"@
$document = $xml.SelectSingleNode('//root/document')
$document.OuterXml

Or to retrieve all document nodes:

$xml = [xml]@"
<root>
    <apphdr></apphdr>
    <document>doc1</document>
    <document>doc2</document>
</root>
"@
$documents = $xml.SelectNodes('//root/document')

CodePudding user response:

Let's create a sample XmlDocument (alias xml):

$xml = [xml] @'
<root>
    <apphdr></apphdr>
    <document><child/></document>
</root>
'@

Create a new XmlDocument, import the document node and append it as the first child (the document element).

$newXml = [xml]::new()
$newNode = $newXml.ImportNode( $xml.root.document, $true )
$newXml.AppendChild( $newNode )
$newXml.Save("$PWD\NewDocument.xml")

Note that the AppendChild call is important, because after ImportNode, the element is not yet associated with a location within the new document.

  • Related