如何从指定目录获取多个XML文件的列表,并且每个文件使用powershell在第二个根节点下添加元素?
实施例:
我想在FIRST <LastName>SomeName</LastName>
元素中添加<Names>
:
<People>
<Names>
<FirstName>someFirstName</FirstName>
</Names>
<Names>
<FirstName>myFirstName</FirstName>
<Address>SomeAddress</Address>
</Names>
</People>
将成为:
<People>
<Names>
<LastName>SomeName</LastName>
<FirstName>someFirstName</FirstName>
</Names>
<Names>
<FirstName>myFirstName</FirstName>
<Address>SomeAddress</Address>
</Names>
</People>
答案 0 :(得分:7)
您可以使用CreateElement
和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)
}
如果您运行PowerShell V2,则无需使用属性PsBase
:
$lastName.InnerText = 'SomeName'
肯定有其他方法,但这很容易。
如果节点在xml中更深,你可以像这样使用Xpath(都找到第一个Names
节点):
$node = (Select-Xml -Xml $x -XPath '//Names[1]').Node
$node = (Select-Xml -Xml $x -XPath '//Names[position()=1]').Node