Jason94
Jason94

Reputation: 13620

Using XPath to read xml

I have this XML:

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <book id="ISBN-NUMBER">
    <title>
      The Autobiography of Benjamin Franklin
    </title>
    <author type="major">
      <first-name>
        Benjamin
      </first-name>
      <last-name>
        Franklin
      </last-name>
    </author>
    <price>
      8.99
    </price>
  </book>
  <book id="ISBN-NUMBER">
    <title>
      The Confidence Man
    </title>
    <author type="major">
      <first-name>
        Herman
      </first-name>
      <last-name>
        Melville
      </last-name>
    </author>
    <price>
      11.99
    </price>
  </book>
  <book id="ISBN-NUMBER">
    <title>
      The Gorgias
    </title>
    <author type="major">
      <name>
        Plato
      </name>
    </author>
    <price>
      9.99
    </price>
  </book>
</bookstore>

How do i read it with XPath? I've used:

XPathDocument doc = new XPathDocument(stream);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator node = nav.Select("bookstore/book");

while (node.MoveNext())

but how do i move on from here? i guess i need a swtich statement to swtich if node is title, author, and price. if book then i need to read books id, same with author and type.

Upvotes: 2

Views: 1318

Answers (1)

SoWhat
SoWhat

Reputation: 5622

You can use node.Select('//title') to get the title, I suppose. I'm not sure how this works in C#, but common xpaths are as follows

  • //bokstore/book selects book nodes.
  • //bookstore/book/title selects the title node
  • //bookstore/book[n]/* selects all the all the child nodes of nth node.

Upvotes: 2

Related Questions