下面介绍的示例创建一个XmlDocument对象,加载磁盘上的一个文档,再从标题元素中加载带有数据的列表框,这类似于XmlReader一节的示例,区别是本例选择要使用的节点,而不是像XmlReader示例那样浏览整个文档。
下面是该示例的代码,与XmlReader示例相比,这个示例是比较简单的(该文件在下载的DOMSample1文件夹中):
private
void
button1_Click(
object
sender, System.EventArgs e) 
...
{
// 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();
如果这就是我们需要完成的
工作
,使用XmlReader加载列表框就是一种非常高效的方式,原因是我们只浏览一次文档,就完成了处理。这就是XmlReader的工作方式。但如果要重新查看某个节点,最好使用XmlDocument。扩展该示例,添加另一个事件处理程序(即DOMSample2):
private
void
listBox1_SelectedIndexChanged(
object
sender, System.EventArgs e) 
...
{
//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");
}
下面简要介绍一下SelectSingleNode()方法,它是XmlDocument类的Xpath实现,SelectSingleNode ()和 SelectNodes()都是在XmlNode中定义的,而XmlDocument是基于XmlNode的。SelectSingleNode()返回一个XmlNode,SelectNodes()返回一个XmlNodeList。System.Xml.XPath命名空间包含许多Xpath实现。
1977

被折叠的 条评论
为什么被折叠?



