[英]Using loops to AppendChild nodes in XML with powershell
我有一些看起来像这样的xml...
<process>
<stage><stage />
<stage><stage />
<stage><stage />
<process />
我正在尝试向每个节点添加一个子节点并添加一个新节点,该节点被调用以获得这样的东西......
<process>
<stage>
<display><display />
<stage />
<stage>
<display><display />
<stage />
<stage>
<display><display />
<stage />
<process />
我在Powershell中写了这个
[XML]$Document = Get-Content "File Path"
$varChild = $Document.CreateElement("display" , $Document.NamspaceURI)
$counter = 0
do {
$Document.process.stage[$counter].AppendChild($var)
$counter += 1
} while ($counter -lt $Document.process.stage.count)
我的故障排除表明发生的事情是该节点被附加到第一阶段节点,但随后它被删除并添加到第二阶段节点......我不知道为什么或如何将它添加到所有节点阶段节点。
您可以使用示例 XML 执行以下操作:
[XML]$Document = Get-Content "File Path"
$Document.process.SelectNodes("//stage") | ForEach-Object {
$node = $Document.CreateNode("element","display",$Document.NamspaceURI)
$_.AppendChild($node)
}
解释:
您将 XML 内容转换为XMLDocument
。 使用带有 XPath 的SelectNodes()
方法来选择您的stage
节点。 为每次迭代创建一个新节点并将其附加到当前stage
节点 ( $_
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.