Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath dates comparison

I'm trying to filter elements based on an attribute that is a date in the format yyyy-MM-dd.

My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <article title="wired" pub-date="2010-11-22" />
  <article title="Plus 24" pub-date="2010-11-22" />
  <article title="Finance" pub-date="2010-10-25" />
</root>

My xpath attempt:

'//article[xs:date(./@pub-date) > xs:date("2010-11-15")]'

Using xpath 2.0 - would avoid adding a schema unless absolutely necessary.

From comments:

I believe I must be missing something then. Is it possible that I need to specify something else for xs:date to work? Maybe a xs: namespace definition?

like image 458
Razor Avatar asked Dec 03 '10 16:12

Razor


People also ask

How to compare dates in XPath?

XPath 1.0 only supports number comparison. If your date format is yyyy-mm-dd then you can use e.g. that way the date is converted to a number first and then the number is compared.

What is XPath function?

XPath can be used to navigate through elements and attributes in an XML document. XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath contains a library of standard functions. XPath is a major element in XSLT and in XQuery.


1 Answers

In both XPath 1.0 and 2.0 you can use:

//article[number(translate(@pub-date,'-','')) > 20101115]

Your XPath 2.0 expression is correct, using Saxon 9.0.3 this transformation:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xsl:template match="/">
      <xsl:sequence select="//article[xs:date(./@pub-date) > xs:date('2010-11-15')]"/>
    </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<root>
  <article title="wired" pub-date="2010-11-22" />
  <article title="Plus 24" pub-date="2010-11-22" />
  <article title="Finance" pub-date="2010-10-25" />
</root>

produces the wanted, correct result:

<article title="wired" pub-date="2010-11-22"/>
<article title="Plus 24" pub-date="2010-11-22"/>
like image 150
Dimitre Novatchev Avatar answered Sep 30 '22 09:09

Dimitre Novatchev