Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through xml elements

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.

Then check for an attribute of SID on the element.

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.

I know I am way off but hope you can help.

like image 508
adean Avatar asked Dec 05 '12 21:12

adean


People also ask

Can you loop in XML?

An XML document (or a section of an XML document) is passed into the For Each loop in a business process variable. An iteration variable holds the current element being processed in the For Each loop, for the life of the loop. This section describes how to add this looping logic to your business process.

How do I iterate over an XML tag in Python?

To iterate over all nodes, use the iter method on the ElementTree , not the root Element. The root is an Element, just like the other elements in the tree and only really has context of its own attributes and children. The ElementTree has the context for all Elements.


2 Answers

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               
like image 193
Keith Hill Avatar answered Oct 05 '22 02:10

Keith Hill


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)
like image 37
Brandon Hawbaker Avatar answered Oct 05 '22 01:10

Brandon Hawbaker