I am trying to construct a XPath Expression to obtain the prices of all the albums, which were published at least 5 years ago. The XML document has the following structure:
<catalogue>
<album>
<year>1990</year>
<price>7.99</price>
...
</album>
</catalogue>
I tried with the following, but obviously, it has a problem:
string xPathExpression = "album[year<year-from-date(current-date())-5]/price";
This does not work either:
string xPathExpression = "album[year<year-from-date("2010-07-07")]/price";
It may be some namespace related issue or something. I found the following example, which I am not exactly sure how to implement on practice:
year-from-date(xs:date("2005-04-23"))
I am using C#, and more specifically XmlDocument(SelectNodes())
.
year-from-date()
and current-date()
are XPath 2.0 functions. .NET's built-in XML libraries, including XmlDocument
, only support XPath 1.0.
In the case of year-from-date()
, you can just use substring()
:
album[year < substring("2010-07-07", 1, 4)]/price
If you need a function that returns the current date, you can create a custom function resolver. This is a bit of a hassle to set up, but it will allow you to define XPath functions that do pretty much anything.