1

I have a XML documents which I would like to extract some data from using XPath. Here is a block in the xml that I'm interested in:

<SalesPrice ElementId="719304324">
    <CountryCodeA2>DE</CountryCodeA2>
    <CurrencyISOCode>EUR</CurrencyISOCode>
    <ValidFrom>2016-10-21T09:39:16.000+02:00</ValidFrom>
    <CancelDate>2016-10-25T09:39:16.000+02:00</CancelDate>
    <Amount>3595</Amount>
</SalesPrice>

I'm trying to get all <SalesPrice> nodes that are valid based on their <ValidFrom> and <CancelDate> values. But, the issue is that not all <SalesPrice> nodes have a <CancelDate> tag and my query below doesn't work:

/SalesPrice[ValidFrom > 2016-10-23T11:15:50+00:00 and CancelDate < 2016-10-23T11:15:50+00:00]

So, what is the right query to get all SalesPrices even if their CancelDate is missing?

Armin Sam
  • 903
  • 9
  • 23

1 Answers1

2

Assuming the following XML:

<root>
  <a>
    <b>1</b>
  </a>
  <a/>
</root>

The following XPath expression will select both a nodes:

//a[not(b) or b = 1]
Markus
  • 3,155
  • 2
  • 23
  • 33
  • Thanks! That's exactly what I was looking for. I now have another issue when I try to compare dates ... do you know what is the best way to compare dates in XPath queries? – Armin Sam Nov 04 '16 at 11:52
  • @ArminSam Which version of XPath? (See also http://stackoverflow.com/questions/4347320/xpath-dates-comparison.) – Markus Nov 04 '16 at 11:53
  • XPath version 1.0 – Armin Sam Nov 04 '16 at 11:57
  • @ArminSam Maybe your XPath implementation supports some kind of extension mechanism which you can use, but otherwise you're pretty much out of luck using XPath 1.0, AFAIK. XPath 2.0 is what you need. – Markus Nov 04 '16 at 12:42
  • You can use substring-before to extract the date part of the dateTime, then translate() to remove the hyphens, this gives you an 8-digit string like 20161104 which you can compare as if it were a number. – Michael Kay Nov 04 '16 at 12:57
  • 1
    @MichaelKay The XML snippet in the question contains ISO timestamps. To correctly compare them (including e.g. correct handling of the time zone) using XPath 1.0 is not something which is easily done by string manipulation. – Markus Nov 04 '16 at 13:00
  • @Markus, you're right. Seems like there is no way I can reliably compare the dates in XPath 1.0. So I decided to do the validation in PHP rather than in XPath query. – Armin Sam Nov 04 '16 at 14:03