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

Java生成XML遇org.xml.sax.SAXParseException错误求助

问题根源与修复方案

嘿,我一眼就看出你问题出在哪了——这个SAXParseException错误的核心原因是你处理retXML的方式完全违背了XML的基本语法规范,还不小心覆盖了自己原本构建好的合法XML文档。

先拆解下错误:

Severe: [Fatal Error] :2:2: The markup in the document following the root element must be well-formed.

这个错误直白说就是你解析的XML内容有多个根元素,而XML要求必须有且仅有一个根节点。

看你的代码逻辑:

  1. 你先创建了一个完整的XML文档,有<XML>作为根节点,里面还包含<GeneratedSet>、<Questions>这些结构,完全合法。
  2. 但当add != null时,你调用gm.additionQ()得到的retXML是一串没有根节点包裹的<Question>...</Question>节点集合(比如<Question ...></Question><Question ...></Question>)。
  3. 然后你用db.parse(is)把这串内容解析成新的Document并覆盖了原来的doc——解析器看到的是多个独立的<Question>根节点,直接触发语法错误。

修复步骤

你不需要重新解析retXML来覆盖原文档,而是应该把生成的<Question>节点添加到你原本构建好的<Questions>元素下面。下面是修改后的核心代码:

替换你原来的这段错误代码:

if(add != null){
    InputSource is = new InputSource();
    genMaths gm = new genMaths();
    retXML = gm.additionQ(leve, 2, numOfQues, 0);
    is.setCharacterStream(new StringReader(retXML));
    doc = db.parse(is);
    //doc = db.parse(new InputSource(new StringReader(is.toString())));
}

改成:

if(add != null){
    genMaths gm = new genMaths();
    retXML = gm.additionQ(leve, 2, numOfQues, 0);
    // 给零散的Question节点套个临时根,方便解析
    String tempWrappedXml = "<TempRoot>" + retXML + "</TempRoot>";
    InputSource is = new InputSource(new StringReader(tempWrappedXml));
    Document tempDoc = db.parse(is);
    
    // 找到原文档里的Questions元素
    Element targetQuestionsElement = (Element) doc.getElementsByTagName("Questions").item(0);
    // 把临时文档里的Question节点导入到原文档,再添加进去
    NodeList questionNodes = tempDoc.getElementsByTagName("Question");
    for(int i=0; i<questionNodes.getLength(); i++){
        Node importedNode = doc.importNode(questionNodes.item(i), true);
        targetQuestionsElement.appendChild(importedNode);
    }
}

另外,你的forwardQ方法里还有个小bug,会导致生成的XML标签不合法:

if ( type == 1 ) {
    retXML.append("' Answer='"+ answer + "'&gt;");
}

这里的&gt;是多余的,应该改成'>,这样生成的<Question>标签才是正确的:

if ( type == 1 ) {
    retXML.append("' Answer='"+ answer + "'>");
}

不然会生成<Question Text='...' Answer='...'&gt;</Question>这种格式错误的标签。

为什么这个修复能解决问题?

  • 我们没有丢弃原本构建好的合法XML结构,只是把生成的Question节点插入到正确的位置。
  • 通过给零散的Question节点套临时根,让解析器能合法解析这些节点,再导入到原文档中,既遵守了XML语法,又实现了你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:22:13