Loop through xml elements

别来无恙 提交于 2019-12-03 12:32:03

Use XPATH instead to find all nodes with a SID attribute like so:

$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               

You can also reference the child nodes when you are iterating through the childNodes:

$j.LocalName (the name of the child element)
$j.InnerXml  (the Xml content of the child node)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!