如何使用XPathNodeIterator遍历XML文件中的项目列表?

时间:2020-03-06 14:37:18  来源:igfitidea点击:

这是我的XML文件的示例(稍作修改,但我们明白了):

<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>

加载我的应用程序(VB.NET应用程序)时,我想遍历主机列表及其属性,并将它们添加到集合中。我希望可以为此使用XPathNodeIterator。我在网上找到的示例似乎有些混乱,我希望这里的人可以使事情变得更清楚。

解决方案

我们可以将它们加载到XmlDocument中,并使用XPath语句填充NodeList ...

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

然后遍历节点

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
        }