You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用Xerces DOMParser解析嵌套XML仅获第一条内容的问题

问题分析

你遇到的问题很直观:代码只提取了第一条<req:message>的内容,原因是在处理req:message节点列表时,你直接取了索引为0的元素,没有遍历所有节点。

修复方案

只需要修改parseXmlData方法里处理req:message节点的逻辑,把单个取值改成循环遍历所有req:message元素即可。另外还要修正代码里的拼写错误(Exceprtion → Exception),同时建议添加异常打印方便排查问题。

修改后的完整代码如下:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class XmlParser {
    public static String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof org.w3c.dom.CharacterData) {
            org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;
            return cd.getData();
        }
        return "";
    }

    private static String parseXmlData() throws ParserConfigurationException, SAXException, IOException {
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><req:messages xmlns:req=\"http://hp.com/ecc/request/\"><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Null pointer exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Arithmetic exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Class not found exception occured.</req:message></req:messages>";
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(str));
        Document doc = db.parse(is);
        NodeList nodes = doc.getElementsByTagName("req:messages");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            NodeList messageNodes = element.getElementsByTagName("req:message");
            // 遍历所有req:message节点,提取每条错误信息
            for (int j = 0; j < messageNodes.getLength(); j++) {
                Element line = (Element) messageNodes.item(j);
                sb.append(getCharacterDataFromElement(line) + System.lineSeparator());
            }
        }
        return sb.toString();
    }

    public static void main(String args[]) {
        try {
            String data = parseXmlData();
            System.out.println(data);
        } catch (Exception e) { // 修正拼写错误
            e.printStackTrace(); // 添加异常打印,方便排查问题
        }
    }
}
关键改动说明
  1. 新增内层循环:针对req:message的节点列表(messageNodes)添加循环,遍历所有索引,确保每一条错误信息都被提取。
  2. 修正拼写错误:把Exceprtion改为正确的Exception,并添加e.printStackTrace(),方便后续定位异常问题。
  3. 变量名优化:将原来的name改为messageNodes,让变量含义更直观易懂。

运行修改后的代码,就能得到你期望的输出:

Null pointer exception occured.
Arithmetic exception occured.
Class not found exception occured.

内容的提问来源于stack exchange,提问作者Dheeraj Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:44:30