如何从指定目录中获取多个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>
最佳答案
您可以使用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
关于powershell - 使用Powershell编辑多个XML文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324882/