简体   繁体   English

使用 powershell 在 XML 中使用循环来追加子节点

[英]Using loops to AppendChild nodes in XML with powershell

I have some xml that looks like this...我有一些看起来像这样的xml...

<process>

<stage><stage />
<stage><stage />
<stage><stage />

<process />

I am trying to add a childnode to each of those nodes and add a new node called to get something like this....我正在尝试向每个节点添加一个子节点并添加一个新节点,该节点被调用以获得这样的东西......

<process>

<stage>
<display><display /> 
<stage />
<stage>
<display><display /> 
<stage />
<stage>
<display><display /> 
<stage />

<process />

I wrote this in Powershell我在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)

My troubleshooting has revealed that what is happening is that the node gets appended to the First stage node BUT THEN it gets removed and added to the second stage node......I have no idea why or how to add it to all of the stage nodes.我的故障排除表明发生的事情是该节点被附加到第一阶段节点,但随后它被删除并添加到第二阶段节点......我不知道为什么或如何将它添加到所有节点阶段节点。

You can do the following with your example XML:您可以使用示例 XML 执行以下操作:

[XML]$Document = Get-Content "File Path"
$Document.process.SelectNodes("//stage") | ForEach-Object {
    $node = $Document.CreateNode("element","display",$Document.NamspaceURI)
    $_.AppendChild($node)
}

Explanation:解释:

You convert your XML content into an XMLDocument .您将 XML 内容转换为XMLDocument Use the SelectNodes() method with an XPath to select your stage nodes.使用带有 XPath 的SelectNodes()方法来选择您的stage节点。 Create a new node for each iteration and append it to the current stage node ( $_ ).为每次迭代创建一个新节点并将其附加到当前stage节点 ( $_ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM