viktorgt
viktorgt

Reputation: 273

XPath expression evaluation error

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.

Upvotes: 5

Views: 546

Answers (2)

Marcus
Marcus

Reputation: 6107

If you look at the XPath spec at http://www.w3.org/TR/xpath/#NT-Step we can see that the Step production is defined as:

Step  ::=  AxisSpecifier NodeTest Predicate*    
         | AbbreviatedStep

In other words, a predicate can not follow an abbreviated step, such as . or .. I would assume that the implementation is therefore (strictly) correct. Perhaps XMLSpy is a bit more liberal in its interpretation and simply always expands .. to parent:node()?

Upvotes: 0

Anirudha
Anirudha

Reputation: 32787

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

Upvotes: 1

Related Questions