如何基于XPath获取的节点列表实现多数值求和?
How to Sum Numeric Values from XPath-Matched Nodes
Got it, let's walk through two solid ways to calculate the total sum of those Cost node values you've targeted.
Option 1: Iterate Through the NodeList (Manual Summation)
Since you already have the NodeList of all <Cost> nodes, you can loop through each one, extract its text content, convert it to a numeric type, and accumulate the total. This is great if you need to add extra logic (like validation) for each node along the way.
Here's the code to implement this:
double total = 0.0; for (int i = 0; i < nl.getLength(); i++) { Node costNode = nl.item(i); // Get the text content of the Cost node (e.g., "12", "3.2") String costText = costNode.getTextContent().trim(); try { // Convert to double and add to total double costValue = Double.parseDouble(costText); total += costValue; } catch (NumberFormatException e) { // Handle cases where the text isn't a valid number System.err.println("Invalid numeric value in Cost node: " + costText); e.printStackTrace(); } } // Print or use the total sum System.out.println("Total sum: " + total);
Option 2: Use XPath's Built-in sum() Function (Elegant & Efficient)
Instead of fetching a NodeList first, you can let XPath do the summation directly with its sum() function. This cuts down on code and leverages XPath's optimized handling of node sets.
Here's how to adjust your code for this approach:
// Compile an XPath expression that calculates the sum directly XPathExpression sumExpr = xpath.compile("sum(XML/Cat/Item/Cost)"); // Evaluate as a NUMBER type to get the total sum Double totalSum = (Double) sumExpr.evaluate(doc, XPathConstants.NUMBER); // Output the result System.out.println("Total sum: " + totalSum);
Quick Notes:
- The
sum()function automatically handles numeric values (integers and decimals like 3.2) in your XML. - If any
<Cost>node has non-numeric content,sum()will treat it asNaN, so you might want to add validation or adjust the XPath to filter valid nodes (e.g.,sum(XML/Cat/Item/Cost[number(.) = .])to only include nodes with valid numbers).
内容的提问来源于stack exchange,提问作者YerivanLazerev
相关产品推荐
相关产品推荐

