Using powershell to edit multiple XML files

How can I get a list of several XML files from the specified directory and for each file add an element under the second root node using powershell?

Example: I want to add <LastName>SomeName</LastName> to the FIRST <Names> element:

 <People> <Names> <FirstName>someFirstName</FirstName> </Names> <Names> <FirstName>myFirstName</FirstName> <Address>SomeAddress</Address> </Names> </People> 

It will become:

 <People> <Names> <LastName>SomeName</LastName> <FirstName>someFirstName</FirstName> </Names> <Names> <FirstName>myFirstName</FirstName> <Address>SomeAddress</Address> </Names> </People> 
+4
source share
1 answer

You can do this using the CreateElement and AppendChild

 Get-ChildItem c:\temp\ *.xml | % { $xml = [xml](Get-Content $_.fullname) $lastName = $xml.CreateElement('LastName') $lastName.PsBase.InnerText = 'SomeName' $null = $xml.People.Names[0].AppendChild($lastName) $xml.Save($_.FullName) } 

If you run PowerShell V2, you do not need to use the PsBase property:

  $lastName.InnerText = 'SomeName' 

There are, of course, other ways, but this one is pretty simple.


In case node is deeper in xml, you can use Xpath like this (both find Names node first):

 $node = (Select-Xml -Xml $x -XPath '//Names[1]').Node $node = (Select-Xml -Xml $x -XPath '//Names[position()=1]').Node 
+6
source

Source: https://habr.com/ru/post/1302216/


All Articles