c#解析XML节点与XPathNavigator

本文关键字:XPathNavigator 节点 XML 解析 | 更新日期: 2023-09-27 18:15:16

我将这个示例XML保存在books.xml中:

<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
</catalog>

我已经创建了一个文档和导航器,如下所示:

var document = new XPathDocument(@"books.xml");
var navigator = document.CreateNavigator();
var books = navigator.Select("/catalog/book");

我正在尝试查看图书节点并解析节点上下文。我可以读取属性,但不知道如何读取节点的值:

while (books.MoveNext())
{
    var location = books.Current;
    var book = new Book();
    book.Id = location.GetAttribute("id", "");
                    
    // this line throws an exception.
    book.Title = (string)location.Evaluate("title/text()") ;
}

有人能告诉我文档中遗漏了什么吗?

请我知道XElement, XmlDocument和XmlTextReader解析方法,但需要弄清楚XPathNavigator如何工作以进行性能比较。

TIA。

c#解析XML节点与XPathNavigator

要获取节点及其值,您应该使用SelectSingleNode()方法,如下所示…

var node = location.SelectSingleNode("title");
book.Title = node != null ? node.Value : string.Empty;

关于性能,这里有一些之前的问题:

哪一个是最好的性能明智:XPathNavigator与XPath vs Linq到Xml查询?

XPathNavigator和XmlReader之间的速度差异有多大?

你试过XmlReader吗?

var reader = new XmlReader("");
while(reader.ReadToFolowing("book")){
    reader.ReadInnerXml();
}