Replacing XML Nodes in PowerShell

I have two XML files (File1.xml, File2.xml). File2.xml is a subset of File1.xml.

File1.xml has the following nodes:

<parentnode> <item id="GUID1"> <Text>Some Text</Text> </item> <item id="GUID2"> <Text>Here's some more text</Text> </item> </parentnode> 

The2.xml file has:

 <parentnode> <item id="GUID1"> <Text>Some Replacement Text</Text> </item> </parentnode> 

I want to take an element with GUIDx in File1.xml and replace it with a GUIDx element from File2.xml. Essentially, I want to take the replacement text in File2.xml and paste it into the corresponding node element in File1.xml

How to do it in PowerShell?

+6
xml powershell
source share
1 answer

Suppose I have the first xml in the variable $edited , and the second in $new . Then you can change the value in the element with GUID1 via

 $edited.parentnode.item | ? { $_.id -eq 'guid1' } | % { $_.Text = $new.parentnode.item.Text } # and save the file $edited.Save('d:\File1.xml') # see the changes gc d:\File1.xml 

If you have more elements to replace, you can use nested pipelines:

 $edited = [xml]@" <parentnode> <item id="GUID1"><Text>Some Text</Text></item> <item id="GUID2"><Text>Here's some more text</Text></item> <item id="GUID3"><Text>Here's some more text</Text></item> <item id="GUID10"><Text>Here's some more text</Text></item> </parentnode> "@ $new = [xml] @" <parentnode> <item id="GUID1"><Text>new Guid1</Text></item> <item id="GUID2"><Text>new Guid2</Text></item> <item id="GUID3"><Text>new Guid3</Text></item> <item id="GUID4"><Text>new Guid4</Text></item> <item id="GUID5"><Text>new Guid5</Text></item> </parentnode> "@ $new.parentnode.item | % { ,($_.id,$_.Text)} | % { $id,$text = $_; $edited.parentnode.item | ? { $_.id -eq $id } | % { $_.Text = $text } } 

or foreach , which is more readable here:

 foreach($i in $new.parentnode.item) { $edited.parentnode.item | ? { $_.id -eq $i.Id } | % { $_.Text = $i.Text } } 
+5
source share

All Articles