我有一个XML文件,其基本结构如下:
<list>
<section>
<rule>
<name>blah</name>
<sources>
<source>
<name>blahsource</name>
</source>
</sources>
</rule>
</section>
</list>
我将文件作为XMl对象导入Powershell,如下所示:
$firewallSections = [xml] (Get-Content "$PSScriptRoot\ExportedRules.xml")
然后我循环修改这样的条目:
foreach ($section in $firewallSections.list.section)
{
DoesSomeThingHere()
}
我需要做的是使用PrependChild以反向顺序将每个$ section添加到新的XML对象。理想情况下是这样的:
$reversed.PrependChild($section)
那么我可以循环:
foreach($section in $reversed.section)
我只是无法弄清楚如何做到这一点。我一直遇到错误:
Exception calling "PrependChild" with "1" argument(s): "The node to be inserted is from a different document context."
答案 0 :(得分:1)
尝试使用$reversed.PrependChild($reversed.OwnerDocument.ImportNode($section, 1))
。
答案 1 :(得分:0)
我按照我想要的方式工作。首先,我必须像这样定义变量:
$reversed = [XML] "<list></list>"
然后我在foreach循环中添加了这一行:
$reversed.DocumentElement.PrependChild($reversed.ImportNode($section, 1)) | out-null
感谢您的帮助!