下面介绍的示例创建一个XmlDocument对象,加载磁盘上的一个文档,再从标题元素中加载带有数据的列表框,这类似于XmlReader一节的示例,区别是本例选择要使用的节点,而不是像XmlReader示例那样浏览整个文档。
下面是该示例的代码,与XmlReader示例相比,这个示例是比较简单的(该文件在下载的DOMSample1文件夹中):
...{
// doc is declared at the module level
// change path to match your path structure
doc.Load("../../../books.xml");
// get only the nodes that we want
XmlNodeList nodeLst=doc.GetElementsByTagName("title");
// iterate through the XmlNodeList
foreach(XmlNode node in nodeLst) listBox1.Items.Add(node.InnerText);
}
注意,我们在本节的示例中添加了模块级的声明:
private XmlDocument doc=new XmlDocument();
...{
//create XPath search string
string srch="bookstore/book[title='" + listBox1.SelectedItem.ToString()
+ "']";
//look for the extra data
XmlNode foundNode = doc.SelectSingleNode(srch);
if(foundNode != null)
MessageBox.Show(foundNode.InnerText);
else
MessageBox.Show("Not found");
}
在这个示例中,与上一个示例一样,从books.xml 文档中加载了带有标题的列表框。单击列表框,会引发SelectedIndexChanged()事件,获取列表框中所选项的文本(书名),创建一个XPath 语句,把它传送给doc对象的SelectSingleNode() 方法,该方法返回title是书名的一部分的book元素(foundNode)。在消息框中显示节点的InnerText。继续单击列表框中的
下面简要介绍一下SelectSingleNode()方法,它是XmlDocument类的Xpath实现,SelectSingleNode ()和 SelectNodes()都是在XmlNode中定义的,而XmlDocument是基于XmlNode的。SelectSingleNode()返回一个XmlNode,SelectNodes()返回一个XmlNodeList。System.Xml.XPath命名空间包含许多Xpath实现。