<?xml version="1.0"?>
-<bookstore>
<book >
<title>aaaa</title>
-<author >
<first-name>firts</first-name>
<last-name>last</last-name>
</author>
<price>8.23</price>
<otherbooks>
<book >
<title>bbb</title>
<price>18.23</price>
</book>
<book >
<title>ccc</title>
<price>11.22</price>
</book>
</otherbooks>
</book>
</bookstore>
I have selected all books form xml file. How to select title, author( first and last name ) and price for each book with use of XPath?
xPathDoc = new XPathDocument(filePath);
xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator book in xPathIterator)
{
??
}
Use SelectSingleNode() and Value:
XPathDocument xPathDoc = new XPathDocument(filePath);
XPathNavigator xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator book in xPathIterator)
{
XPathNavigator nav = book.SelectSingleNode("title");
string title = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("author/first-name");
string authorFirstName = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("author/last-name");
string authorLastName = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("price");
string price = nav==null ? string.Empty : nav.Value;;
Console.WriteLine("{0} {1} {2} {3}", title, authorFirstName, authorLastName, price);
}
You can use LINQ2XML
XElement doc=XElement.Load("yourXML.xml");//loads your xml
var bookList=doc.Descendants().Elements("book").Select(
x=>//your book node
new{
title=x.Element("title").Value,
author=new //accessing your author node
{
firstName=x.Element("author").Element("first-name").Value,
lastName=x.Element("author").Element("last-name").Value
},
price=x.Element("price").Value
}
);
bookList now have all the elements you want
So, you can do this now
foreach(var book in bookList)
{
book.title;//contains title of the book
book.author.firstName;//contains firstname of that book's author
book.author.lastName;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With