gpt4 book ai didi

powershell - 使用Powershell编辑多个XML文件

转载 作者:行者123 更新时间:2023-12-04 18:16:33 24 4
gpt4 key购买 nike

如何从指定目录中获取多个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>

最佳答案

您可以使用CreateElementAppendChild方法进行操作

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com