Shortest XPath to find minimum/maximum of sibling dateTime nodes

letmaik picture letmaik · Aug 30, 2010 · Viewed 8.4k times · Source

I have the following simple xml:

<root>
 <item>
  <d>2002-05-30T09:00:00</d>
 </item>
 <item>
  <d>2005-05-30T09:00:00</d>
 </item>
 <item>
  <d>2003-05-30T09:00:00</d>
 </item>
</root>

Now I want to find the minimum or maximum dateTime node using XPath.

My solution at the moment is:

/root/item[not(number(translate(./d, 'TZ:-', '.')) <= number(translate(following-sibling::item, 'TZ:-', '.')))][not(number(translate(./d, 'TZ:-', '.')) <= number(translate(preceding-sibling::item, 'TZ:-', '.')))][1]/d

It works but is is ugly as hell and not very efficient. Basically it converts the dateTime to a number and then compares them with each other. I adapted this from here.

What is the nicest way to do this?

Cheers

neo

Answer

user357812 picture user357812 · Aug 30, 2010

You could not in XPath 1.0 if you will not know in advance the number of item because every function wich has a no node-set argument cast its argument taking the first node in node-set, and order comparison operator doesn't work with strings.

In XPath 2.0 you could use:

max(/root/item/d/xs:dateTime(.))