我试图在MSDN网站上阅读作为示例提供的book.xml文件.
<?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>
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有以下代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
似乎这段代码正在阅读所有内容,但是从这里开始,如果我想要显示所有书籍的标题等,我该如何访问它们?
Dir*_*mar 16
如果更改XPath表达式以选择所有标题节点,则可以迭代标题:
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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,XmlDocument如果您不打算修改文档,则无需创建.使用a XPathDocument通常更轻.
| 归档时间: |
|
| 查看次数: |
20799 次 |
| 最近记录: |