tags:

views:

1384

answers:

2

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.

A: 

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

kitsune
A: 
        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
        }
ckarras