循环遍历 xml 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13732715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through xml elements
提问by adean
I have the following:
我有以下几点:
$aMyArray = $null
[xml]$userfile = Get-Content C:\AppSense\Scripts\AmPolicyConversion\AM_dev.xml
$i = 0
FOREACH ($j in $userfile.ChildNodes){
FOREACH($k in $j.DocumentElement) {
}
$i = $i + 1
}
I am trying to figure out how to loop through each element within powershell.
我想弄清楚如何遍历 powershell 中的每个元素。
Then check for an attribute of SID on the element.
然后检查元素上的 SID 属性。
If exists get attribute value and put that value into an object and for the same element grab second attribute DISPLAYNAME and place into same object. We will create an array of objects.
如果存在,获取属性值并将该值放入一个对象中,对于相同的元素,获取第二个属性 DISPLAYNAME 并放入同一个对象中。我们将创建一个对象数组。
I know I am way off but hope you can help.
我知道我很遥远,但希望你能帮忙。
回答by Keith Hill
Use XPATH instead to find all nodes with a SID attribute like so:
使用 XPATH 来查找具有 SID 属性的所有节点,如下所示:
$objs = @()
$nodes = $userfile.SelectNodes("//*[@SID]")
foreach ($node in $nodes) {
$sid = $node.attributes['SID'].value
$dispName = $node.attributes['DISPLAYNAME'].value
$obj = new-object psobject -prop @{SID=$sid;DISPNAME=$dispName}
$objs += $obj
}
$objs
Here's an example with output:
这是一个带有输出的示例:
$xml = [xml]@"
<doc>
<foo SID='foosid' DISPLAYNAME="foodisp">
<bar SID='barsid' DISPLAYNAME="bardisp"/>
<baz>
<blech SID='blechsid' DISPLAYNAME="blechdisp"/>
</baz>
</foo>
</doc>
"@
$objs = @()
$nodes = $xml.SelectNodes("//*[@SID]")
foreach ($node in $nodes) {
$sid = $node.attributes['SID'].value
$dispName = $node.attributes['DISPLAYNAME'].value
$obj = new-object psobject -prop @{SID=$sid;DISPNAME=$dispName}
$objs += $obj
}
$objs
Outputs:
输出:
SID DISPNAME
--- --------
foosid foodisp
barsid bardisp
blechsid blechdisp
回答by Brandon Hawbaker
You can also reference the child nodes when you are iterating through the childNodes:
您还可以在迭代 childNodes 时引用子节点:
$j.LocalName (the name of the child element)
$j.InnerXml (the Xml content of the child node)

