I try to parse a large XML file and I'm using a lot of relative path for the XPath expressions.
Now I'm running into a trouble with the .net XPath evaluation.
Here a small example which explains my problem:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
</book>
</bookstore>
And here is the code:
static void Main(string[] args)
{
System.Xml.XmlDocument d = new System.Xml.XmlDocument();
d.Load(@"D:\simpleXml.xml");
System.Diagnostics.Trace.WriteLine(d.SelectSingleNode("//price/..[year=\'2005\']").Name);
}
I get the following error message: Additional information: '//price/..[year='2005']' has an invalid token.
For me, it seems to be a valid XPath expression, since other tools like XMLSpy evaluate that expression successfully.
Why not use linq2xml
XDocument doc=XDocument.Load("yourXML");
var bookPrice=doc.Descendants("book")
.Where(x=>x.Element("year").Value=="2005")
.Select(y=>y.Element("price").Value);
//gets the price of the books published in 2005
If you want the xpath version,here it is
"bookstore/book[year='2005']/*/../price"
//gets the price of the books published in 2005
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