Matt Hanson
Matt Hanson

Reputation: 3504

How do I use XPathNodeIterator to iterate through a list of items in an XML file?

This is a sample (edited slightly, but you get the idea) of my XML file:

<HostCollection>
  <ApplicationInfo />
  <Hosts>
    <Host>
      <Name>Test</Name>
      <IP>192.168.1.1</IP>
    </Host>
    <Host>
      <Name>Test</Name>
      <IP>192.168.1.2</IP>
    </Host>
  </Hosts>
</HostCollection>

When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.

Upvotes: 1

Views: 9071

Answers (2)

ckarras
ckarras

Reputation: 5016

        XPathDocument xpathDoc;
        using (StreamReader input = ...)
        {                
            xpathDoc = new XPathDocument(input);
        }

        XPathNavigator nav = xpathDoc.CreateNavigator();
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);

        XPathNodeIterator nodes = nav.Select("/HostCollection/Hosts/Host", nsmgr);

        while (nodes.MoveNext())
        {
           // access the current Host with nodes.Current
        }

Upvotes: 1

kitsune
kitsune

Reputation: 11643

You could load them into an XmlDocument and use an XPath statement to fill a NodeList...

Dim doc As XmlDocument = New XmlDocument()
doc.Load("hosts.xml")
Dim nodeList as XmlNodeList
nodeList = doc.SelectNodes("/HostCollectionInfo/Hosts/Host")

Then loop through the nodes

Upvotes: 2

Related Questions