在 java 中将日期与 Xpath 进行比较

Comparing date with Xpath in java

我有一个 XML 页面,我使用 Java 中的 DOM 对其进行了解析。当我使用 XPath 执行查询时,例如 price <10price >20,我得到了预期的结果。但是,当我尝试按日期进行比较时,我得不到任何结果。 NetBeans 说它成功了,但没有给我任何结果。

此代码来自 XML 页面:

<!?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>

这是我的 Java 代码:

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");
        }
    }
}

我需要做的是将 publish_date 与预定义的日期进行比较。 "//书[publish_date>2000-01-01]/* 像这样

Xpath(至少 1.0)无法比较日期,但您可以使用转换功能将日期按正确的顺序转换为整数:

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