使用XpathNavigator读取C#中的XML文件 [英] Reading XML file in C# with XpathNavigator
本文介绍了使用XpathNavigator读取C#中的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试阅读MSDN网站上作为示例提供的book.xml文件.
I am trying to read the book.xml file provided as an example on the MSDN website.
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
到目前为止,我有以下代码:
I have the following code until now:
static void Main()
{
XmlDocument document = new XmlDocument();
document.Load(@"c:\books.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/bookstore/book");
while (nodes.MoveNext())
{
Console.WriteLine(nodes.Current.HasAttributes);
}
}
似乎这段代码正在读取所有内容,但是从这里开始,如果我只想显示所有书籍的书名等,该如何访问它们?
It seems this code is reading everything, but from here on if I want to display, say, just the titles of all book etc., how do I access them?
推荐答案
如果更改XPath表达式以选择所有标题节点,则可以遍历标题:
You can iterate over the titles if you change the XPath expression to select all title nodes:
XPathDocument document = new XPathDocument(@"c:\tmp\smpl5.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/bookstore/book/title");
foreach (XPathNavigator item in nodes)
{
Console.WriteLine(item.Value);
}
请注意,如果您不打算修改文档,则无需创建 XmlDocument
.使用 XPathDocument
通常更轻巧.
Note that you don't need to create an XmlDocument
if you don't plan to modify the document. Using an XPathDocument
is usually more light-weight.
这篇关于使用XpathNavigator读取C#中的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文