Question

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>
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top