Search code examples
xmlvb.netxelement

How do I properly loop through all XML nodes?


I have an XML document which I would like to use the attributes from each node with a structure like so:

<level1 attr1="value" attr2="value">
   <level2 attr3="value">
      <level3 attr1="value" attr3="value">
      </level3>
    </level2>
   <level2 attr3="value">
      <level3 attr1="value" attr3="value">
      </level3>
   </level2>
   <level2 attr3="value">
      <level3 attr1="value" attr3="value">
      </level3>
   </level2>
</level1>
<level1>
    ....
</level1>

I am trying to loop through each node in the file and record the information from the attributes.

Code:

Dim xml As New XDocument
Dim root As New XElement
xml = XDocument.Load(myFileLoc)
root = xml.Root

For Each level1 in root.Descendants()
    'Do Something with level1 attr'
    For Each level2 in level1.Descendants()
        'Do Something with level2 attr'
         For Each level3 in level2.Descendants()
             'Do Something with level3 attr'
         Next
    Next
Next

I learned quickly that this will loop through the entire document several times because level1 in root.Descendants() will also be all children level2s and level3s.

How can I limit each level1/level2/level3 to only the current node depth? Or, how should I be doing this kind of work?


Solution

  • Mark provided what I was looking for, thank you. Using Elements() rather than Descendants() provided the nodes I was looking to loop through at each level.

    Dim xml As New XDocument
    Dim root As New XElement
    xml = XDocument.Load(myFileLoc)
    root = xml.Root
    
    For Each level1 in root.Elements()
        'Do Something with level1 attr'
        For Each level2 in level1.Elements()
            'Do Something with level2 attr'
             For Each level3 in level2.Elements()
                 'Do Something with level3 attr'
             Next
        Next
    Next