Copying nodes between documents

Nodes (elements, attributes, and so on) may be copied and moved between different XML documents. To bring a node from an external document into another, it must first be imported.

The following example creates two simple XML documents. The first (the variable xml) is the intended destination. The newNodes variable contains a set of elements that should be copied:

[Xml]$xml = @" 
<?xml version="1.0"?> 
<list type='numbers'> 
<name>1</name> 
</list>    
"@ 
[Xml]$newNodes = @" 
<root> 
<name>2</name> 
<name>3</name> 
<name>4</name> 
</root> 
"@ 

To copy the name nodes requires each node to be selected (in turn), imported into the original document, and added to the desired node:

foreach ($node in $newNodes.SelectNodes('/root/name')) {     
    $newNode = $xml.ImportNode($node, $true) 
$null = $xml.list.AppendChild($newNode) 
} 

The ImportNode method requires two parameters: the node from the foreign document (newNodes) and whether or not the import is deep (one level or fully recursive).

The resulting XML can be viewed by inspecting the OuterXml property of the xml variable:

PS> $xml.OuterXml 
<?xml version="1.0"?><list type="numbers"><name>1</name><name>2</name><name>3</name><name>4</name></list> 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.179.100