繁体   English   中英

读取xml文件并使用Java进行求和

[英]Read xml file and make summation with java

我对Java和xml非常陌生。 我正在尝试找到一种方法来求和,但是我不确定如何做到这一点。 我已经尝试了几件事,但是没有用。 非常感谢你的帮助。

for (int i = 0; i < clients.getLength(); i++) {
    Element client = (Element) clients.item(i);
    String name = client.getAttribute("name");
    NodeList transactions = client.getElementsByTagName("transaction");

    for(int j=0; j<transactions.getLength(); j++) {
            Element transaction = (Element) transactions.item(j);
            int amount = Integer.parseInt(transaction.getAttribute("amount"));

    }

    System.out.println("Client name : " +name);
    System.out.println("Sum : " );
}

尝试这个

   for (int i = 0; i < clients.getLength(); i++) {
    Element client = (Element) clients.item(i);
    String name = client.getAttribute("name");
    NodeList transactions = client.getElementsByTagName("transaction");
     int sum =0;
    for(int j=0; j<transactions.getLength(); j++) {
            Element transaction = (Element) transactions.item(j);
            sum = sum + Integer.parseInt(transaction.getAttribute("amount"));

    }

    System.out.println("Client name : " +name);
    System.out.println("Sum : " + sum );
}

使用XPath,这种事情要容易得多(即使您不必使用Java和DOM,也可能不需要)。

XPath xpath = XPathFactory.newInstance().newXPath();
for (int i = 0; i < clients.getLength(); i++) {
    Element client = (Element) clients.item(i);
    int sum = (int)xpath.evaluate("sum(transaction/@amount)", 
                  client, XPathConstants.NUMBER);    
    System.out.println("Client name : " + client.getAttribute("name"));
    System.out.println("Sum : " + sum );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM