如何使用XPathNodeIterator遍历XML文件中的项目列表?
问题描述:
这是一个示例(稍微改动过,但你的想法),我的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。我在网上找到的例子似乎有点混乱,我希望这里有人能够澄清一些事情。
答
你可以把它们加载到一个XmlDocument和使用XPath语句来填补节点列表...
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
}