tags:

views:

32

answers:

2

I am trying to read the book.xml file provided as an example on the MSDN website.

    <?xml version="1.0" encoding="utf-8" ?> 
<bookstore>
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

I have the following code until now:

static void Main()
        {
            XmlDocument document = new XmlDocument();
            document.Load(@"c:\books.xml");

            XPathNavigator navigator = document.CreateNavigator();

            XPathNodeIterator nodes = navigator.Select("/bookstore/book");


            while (nodes.MoveNext())
            {
                Console.WriteLine(nodes.Current.HasAttributes);
            }


        }

It seems this code is reading everything, but from here on if I want to display, say, just the titles of all book etc., how do I access them?

+1  A: 

You can iterate over the titles if you change the XPath expression to select all title nodes:

XPathDocument document = new XPathDocument(@"c:\tmp\smpl5.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator nodes = navigator.Select("/bookstore/book/title");

foreach (XPathNavigator item in nodes)
{
    Console.WriteLine(item.Value);
}

Note that you don't need to create an XmlDocument if you don't plan to modify the document. Using an XPathDocument is usually more light-weight.

0xA3
Thanks! That works brilliantly.
xbonez
Now instead of viewing all titles throughout the xml file, what would be the easiest way of displaying all information about each node? That is, display title, author first name, author last name etc.
xbonez
+1 for recommending xpathdocument
annakata
@xbonez: you'd have to read in each book node and then each bit of info you're interested. Deserialising to a class object is your best bet for reuse.
annakata
A: 

you can also use this "//title" instead of "/bookstore/book"

Akie