我解析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);
为什么会这样?
答案 0 :(得分:2)
XPathConstants.NUMBER
评估为Double
,为了将结果分配给Long
,您需要执行以下操作:
resultSum = ((Double) expr.evaluate(doc, XPathConstants.NUMBER)).longValue();