2008-09-23 85 views
0

這是一個示例(稍微改動過,但你的想法),我的XML文件:如何使用XPathNodeIterator遍歷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。我在網上找到的例子似乎有點混亂,我希望這裏有人能夠澄清一些事情。

回答

1

你可以把它們加載到一個XmlDocument和使用XPath語句來填補節點列表...

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

然後通過節點環

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