-1

I'm trying to iterate through each node in an XML document. I can't seem to figure out how to do this. I'm doing this in PowerShell, but could translate from C#.

foreach ($file in Get-ChildItem ($directoryUrl+"\*.*") -include *.xml)
{
    [xml]$xmlFile = Get-Content $file; #get content from xml file
    Write-Host "Fff";

    $firstNode = $xmlFile.DocumentElement;

    $children = $firstNode.ChildNodes;

Now this gets the children of the first, node which is fine, but it's picking up Random as a child, but I also want it to pick up what's inside the Random XML tag. Like in the details tags.

How can I get this easily in PowerShell?

The XML I'm reading is:

<UserBase> 
  <User> 
    <Name>Kalle</Name> 
  </User> 
  <User> 
    <Name>Becker</Name> 
  </User>
  <User> 
    <Name>Daniel</Name> 
  </User> 
  <User> 
    <Name>Anderson</Name> 
  </User>
  <Random>
    <Details>myself</Details>
    <Details>mysdelf</Details>
  </Random>
</UserBase>
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user3519261
  • 79
  • 1
  • 14
  • To handle multilevel xml you need to use a recursive function. Try AddNode in answer 2 on following webpage. A TreeView is a good way of display an xml file. http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng Sep 28 '15 at 01:48
  • What do you mean by AddNode? – user3519261 Sep 28 '15 at 02:36
  • It is part of answer #2 on the webpage – jdweng Sep 28 '15 at 03:07
  • What about the child nodes of the `` nodes? i.e. do you actually want a list of *all* nodes (including text nodes?), or just specific nodes (which?)? – Ansgar Wiechers Sep 28 '15 at 10:28

1 Answers1

2

Not sure I really understand your question, but to get all nodes from an XML document, you can call XPath to the rescue:

$xml = [xml] @"
    <UserBase> 
      <User> 
        <Name>Kalle</Name> 
      </User> 
      <User> 
        <Name>Becker</Name> 
      </User>
      <User> 
        <Name>Daniel</Name> 
      </User> 
      <User> 
        <Name>Anderson</Name> 
      </User>
      <Random>
        <Details>myself</Details>
        <Details>mysdelf</Details>
      </Random>
    </UserBase>
"@

select-xml $xml -xpath "/descendant-or-self::node()" | 
   where { !$_.Node.Name.Contains("#") }
David Brabant
  • 41,623
  • 16
  • 83
  • 111