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 scroll each element in powershell.

Then check the SID attribute on the element.

If there is a get attribute value and put this value in the object and for the same element take the second DISPLAYNAME attribute and place it in the same object. We will create an array of objects.

I know I'm leaving, but I hope you can help.

+7
source share
2 answers

Use XPATH instead to find all nodes with the SID attribute as follows:

 $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 is an output example:

 $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 
+11
source

You can also refer to child nodes when you iterate through childNodes:

 $j.LocalName (the name of the child element) $j.InnerXml (the Xml content of the child node) 
+2
source

All Articles