Search code examples
javadatexpathxml-parsingdate-comparison

Comparing date with Xpath in java


I have an XML page that I parse using DOM in Java. When I perform a query using XPath, for example price <10 or price >20, I get the expected result. However, I cannot get any results when I try to compare by date. NetBeans says it's successful, but does not give me any results.

This code is from the XML page:

<!?xml version="1.0" encoding="UTF-8"?><catalog ><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications 
with XML.</description>
</book>
<catalog>

This is my Java code:

public class Main {
    public static void main(String[] args) throws XPathExpressionException, FileNotFoundException {

        XPathFactory factory = XPathFactory.newInstance();
        XPath path = factory.newXPath();
        XPathExpression xPathExpression=path.compile("//book[price >10]/* ");
        //| //book[price>10]/*

        File xmlDocument =new File("books.xml");
        InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));

        Object result = xPathExpression.evaluate(inputSource,XPathConstants.NODESET);

        NodeList nodeList = (NodeList)result;

        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.print(nodeList.item(i).getNodeName()+" ");
            System.out.print(nodeList.item(i).getFirstChild().getNodeValue());
            System.out.print("\n");
        }
    }
}

What I need to do is to compare publish_date to a predefined date. "//book[publish_date>2000-01-01]/* something like this


Solution

  • Xpath (at least 1.0) cannot compare dates, but you can turn date into integer with right order, using translate function:

    //book[translate(publish_date,'-','') > 20000101]