2010-09-22 79 views
7

我想读取作为MSDN网站上的示例提供的book.xml文件。用XpathNavigator读取C#中的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> 

我有下面的代码至今:

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); 
      } 


     } 

看来这段代码是阅读一切,但是从现在开始,如果我要显示,也就是说,所有的书等,只有标题,我如何访问它们?

回答

15

可以遍历标题,如果你改变了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); 
} 

请注意,您不需要创建XmlDocument,如果你不打算修改文件。使用XPathDocument通常更轻。

+0

谢谢!这非常出色。 – xbonez 2010-09-22 12:48:10

+0

现在,而不是查看整个XML文件中的所有标题,显示关于每个节点的所有信息最简单的方法是什么?也就是显示标题,作者名字,作者姓氏等 – xbonez 2010-09-22 12:49:39

+1

+1推荐xpathdocument – annakata 2010-09-22 12:50:59

0

您还可以使用此“// title”而不是“/ bookstore/book”