我正在使用以下内容通过XML文件添加相关元素(Parent-Child):
[xml]$fileXml = Get-Content 'c:\example.xml'
$fileXml.Elements | % {
MyAdd-Function $_
}
删除这些元素时,如何确保以相反的顺序迭代?我试过这个并不起作用:
[xml]$fileXml = Get-Content 'c:\example.xml'
[Array]::Reverse($fileXml.Elements) | % {
MyRemove-Function $_
}
我正在考虑将$fileXml.Elements
转换为实际数组,然后进行反转,但我想知道是否有更简单的方法。
答案 0 :(得分:1)
您的方法听起来不错,但考虑到Reverse()
没有返回数组,您必须将Reverse()
和Foreach-Object
分开。
PS > [array]::Reverse.OverloadDefinitions
static void Reverse(array array)
我不确定你从哪里获得Elements
- 属性,但这里是一个PoC:
PS > $xml = [xml]@"
<?xml version="1.0" encoding="UTF-8"?>
<root>
<note>
<to>User1</to>
</note>
<note>
<to>User2</to>
</note>
</root>
"@
#Store the elements in an array
PS > $a = $xml.root.note
PS > $a | % { $_.to }
User1
User2
#Reverse
PS > [array]::Reverse($a)
PS > $a | % { $_.to }
User2
User1