Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using powershell to edit multiple XML files

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

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

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

Will become:

<People>
  <Names>
      <LastName>SomeName</LastName>
      <FirstName>someFirstName</FirstName>
  </Names>
  <Names>
      <FirstName>myFirstName</FirstName>
      <Address>SomeAddress</Address>
  </Names>
</People>
like image 947
Draco Avatar asked Feb 24 '10 09:02

Draco


1 Answers

You can do it using CreateElement and AppendChild method

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)
    }

In case that you run PowerShell V2, you don't need to use property PsBase:

        $lastName.InnerText = 'SomeName'

There are for sure other ways, but this is one is quite easy.


In case that the node would be deeper in xml, you might use Xpath like this (both find first Names node):

$node = (Select-Xml -Xml $x -XPath '//Names[1]').Node
$node = (Select-Xml -Xml $x -XPath '//Names[position()=1]').Node
like image 100
stej Avatar answered Oct 11 '22 01:10

stej