Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath expression evaluation error

Tags:

c#

.net

xml

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.

like image 247
viktorgt Avatar asked Nov 12 '22 19:11

viktorgt


1 Answers

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
like image 70
Anirudha Avatar answered Nov 15 '22 10:11

Anirudha