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:
1 2 3 4 5 6 7 8 9 10 |
SomeAddress |
Will become:
1 2 3 4 5 6 7 8 9 10 11 |
SomeAddress |
Answer:
You can do it using CreateElement
and AppendChild
method
1 2 3 4 5 6 7 8 9 |
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
:
1 2 |
$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):
1 2 3 |
$node = (Select-Xml -Xml $x -XPath '//Names[1]').Node $node = (Select-Xml -Xml $x -XPath '//Names[position()=1]').Node |