XPathExpression无法对数字求和

时间:2017-10-14 13:14:34

标签: java xml xpath

我解析XML并使用XPath想要评估汇总。

我试试:

long resultSum = 0L;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(getOutputFileName());
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
String xPathExpression = "sum(//entries//entry/@field)";
XPathExpression expr = xPath.compile(xPathExpression);
resultSum = (Long) expr.evaluate(doc, XPathConstants.NUMBER);

但是,我有错误:

Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long

在这一行:

resultSum = (Long) expr.evaluate(doc, XPathConstants.NUMBER);

为什么会这样?

1 个答案:

答案 0 :(得分:2)

XPathConstants.NUMBER评估为Double,为了将结果分配给Long,您需要执行以下操作:

resultSum = ((Double) expr.evaluate(doc, XPathConstants.NUMBER)).longValue();