0

我将这个示例 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。

4

2 回答 2

1

要获取节点及其值,您应该使用这样的SelectSingleNode()方法......

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

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

在性能方面哪个是最好的:带有 XPath 的 XPathNavigator 与带有查询的 Linq to Xml?

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

于 2013-05-25T23:48:03.350 回答
0

你试过 XmlReader 吗?

var reader = new XmlReader("");
while(reader.ReadToFolowing("book")){
    reader.ReadInnerXml();
}
于 2013-05-26T00:26:31.080 回答