使用 DOM 从 XML 中总结 Java 中的属性

Summing attributes in Java from XML using DOM

我有这个 XML 文档,我正在编写一个 Java 代码来对文档进行一些操作:

<?xml version="1.0" encoding="ISO-8859-1"?>
<list>
<client name="Bob">
<transaction amount="100"/>
<transaction amount="150"/>
</client>
<client name="Ruth">
<transaction amount="100"/>
<transaction amount="150"/>
<transaction amount="100"/>
</client>
</list>

我想将两个客户的所有金额相加并得到以下结果:

鲍勃:250 露丝:350

目前,我已经编写了这段代码:

NodeList nl = racine.getElementsByTagName("client");
NodeList mn = doc.getElementsByTagName("transaction");
int somme=0; 
    
    
for(int i=0; i<mn.getLength(); i++) {
            
Element transaction = (Element)mn.item(i);
Element client = (Element) nl.item(i);
NodeList nameslist = client.getElementsByTagName("name");
Element nom = (Element) nameslist.item(i);
    
            
int montant = Integer.parseInt(transaction.getAttribute("amount"));
total+=amount; 
System.out.println("Name: " + client.getAttribute("name") + total)

但它不求和,它只取每个客户的第一笔金额。

    NodeList clientNodeList = doc.getElementsByTagName("client");

    for (int i = 0; i < clientNodeList.getLength(); i++) {
        Element client = (Element) clientNodeList.item(i);
        System.out.println(client.getNodeName() + ": " +  client.getAttribute("name"));

        NodeList transactionNodeList = client.getElementsByTagName("transaction");

        int total = 0;
        for (int j = 0; j < transactionNodeList.getLength(); j++) {
            Element transaction = (Element) transactionNodeList.item(j);
            int amount = Integer.valueOf(transaction.getAttribute("amount"));
            total += amount;
        }
        System.out.println("Total: " + total);
    }

这是一段简单的代码。你做错的是你还需要遍历客户端NodeList来获取事务NodeList。