[英]C# Parsing XML node with XPathNavigator
我将此示例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。
要获取节点及其值,应使用像这样的SelectSingleNode()
方法。
var node = location.SelectSingleNode("title");
book.Title = node != null ? node.Value : string.Empty;
关于性能,这里有一些以前的问题:
您是否尝试过XmlReader?
var reader = new XmlReader("");
while(reader.ReadToFolowing("book")){
reader.ReadInnerXml();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.