要理解这些类的用法,最好是查看一下迭代books.xml文档的代码,确定导航是如何工作的。为了使用这些示例,首先需要添加对System.Xml.Xsl 和 System.Xml.XPath命名空间的引用,如下所示:
using System.Xml.XPath;
using System.Xml.Xsl;
这个示例使用了文件booksxpath.xml,它类似于前面使用的books.xml,但booksxpath.xml添加了两本书。下面是窗体代码,这段代码在XPathXSLSample1文件夹中:
private void button1_Click(object sender, System.EventArgs e)
{
//modify to match your path structure
XPathDocument doc=new XPathDocument("..\\..\\..\\booksxpath.xml");
//create the XPath navigator
XPathNavigator nav=doc.CreateNavigator();
//create the XPathNodeIterator of book nodes
// that have genre attribute value of novel
XPathNodeIterator iter=nav.Select("/bookstore/book[@genre='novel']");
while(iter.MoveNext())
{
LoadBook(iter.Current);
}
}
private void LoadBook(XPathNavigator lstNav)
{
//We are passed an XPathNavigator of a particular book node
//we will select all of the descendents and
//load the list box with the names and values
XPathNodeIterator iterBook=lstNav.SelectDescendants
(XPathNodeType.Element, false);
while(iterBook.MoveNext())
listBox1.Items.Add(iterBook.Current.Name + ": "
+ iterBook.Current.Value);
}
在button1_Click()方法中,首先创建XPathDocument(叫做doc),其参数是要打开的文档的文件和路径字符串。下面一行代码创建XPathNavigator:
XPathNavigator nav = doc.CreateNavigator();
本例用Select方法获取genre属性值为novel的所有节点,然后使用MoveNext()方法迭代书籍列表中的所有小说。
要把数据加载到列表框中,使用XPathNodeIterator.Current属性,根据XPathNodeIterator指向的节点,创建一个新的XPathNavigator对象。在本例中,为文档中的一个book节点创建一个XPathNavigator。
LoadBook()方法提取这个XPathNavigator,调用Select方法的另一个重载方法SelectDescendants创建另一个XPathNavigator,这样,XPathNodeIterator就包含了给LoadBook方法发送的book节点的所有子节点。
然后,在这个XPathNodeIterator上执行另一个MoveNext()循环,给列表框加载元素名称和元素值。在执行代码后,显示23-7所示的屏幕图,注意只列出了小说。