質問

I have this sample XML saved in 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>

I have created a document and navigator like so:

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

I am trying to look through the book nodes and parse the node context. I can read the attributes but cannot figure out how to read the values of a node:

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

Anyone with some insights on what I missed from the documentation?

Please I am aware of XElement, XmlDocument and XmlTextReader parsing methods but need to figure out how XPathNavigator works for performance comparison purposes.

TIA.

役に立ちましたか?

解決

To get a node and its value you should use the SelectSingleNode() method like this...

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

On performance, here are some previous questions:

Which is the best for performance wise: XPathNavigator with XPath vs Linq to Xml with query?

How big is the speed difference between XPathNavigator and XmlReader, really?

他のヒント

Have you tried XmlReader?

var reader = new XmlReader("");
while(reader.ReadToFolowing("book")){
    reader.ReadInnerXml();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top