我有这样的XML文件:
<books>
<book>
<id>1</id>
<validFrom>23.11.2012</validFrom>
<validTo>26.09.2012</validTo>
</book>
<book>
<id>2</id>
<validFrom>14.09.2012</validFrom>
<validTo>01.08.2012</validTo>
</book>
我想从这个xml文件中删除所有书籍,其中dateTo的日期在当前日期之前,但我在XPath中遇到查询问题。
我尝试了不同的方式。
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr
= xpath.compile("//book[validTo < fn:current-date()]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
removeFindNodes()
}
如何格式化validTo以便能够与当前日期进行比较?
感谢您的帮助
答案 0 :(得分:1)
xsd:date
期望格式为yyyy-MM-dd
,而您的格式为dd.MM.yyyy
。您可以尝试使用substring
,translate
和concat
的组合来转换格式,但到那时您的XPath表达式会变得稍微复杂一些。另一种解决方案,更容易阅读,是获取所有validTo
个节点,然后与Java进行比较:
XPathExpression expr = xpath.compile("//book/validTo");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
for (int i = 0; i < nodes.getLength(); i++) {
Node validToNode = nodes.item(i);
Date validTo = df.parse(validToNode.getTextContent());
if (validTo.compareTo(now.getTime()) < 0) {
Node bookNode = validToNode.getParentNode();
removeNode(bookNode);
}
}