i have such XML-File:
<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>
I want to remove from this xml file all books, where the date validTo is before current date, but I have problems with query in XPath.
I tried in different ways.
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()
}
How can I format the validTo to be able to compare with current date?
Thanks for your help
xsd:date expects the format to be yyyy-MM-dd, whilst yours is dd.MM.yyyy. You could try to use a combination of substring, translate, and concat to transform your format, but by then your XPath expression would become slightly complicated. An alternative solution, and far easier to read, is to fetch all validTo nodes and then do the comparison with 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With