gpt4 book ai didi

java - appendChild 处的 DOMException

转载 作者:行者123 更新时间:2023-11-29 04:49:35 28 4
gpt4 key购买 nike

我正在尝试通过替换其中的某些元素来使用 DOM 修改 XML 文档,但出现以下异常:

03-10 10:49:20.943: W/System.err(22584):    org.w3c.dom.DOMException
03-10 10:49:20.943: W/System.err(22584): at org.apache.harmony.xml.dom.InnerNodeImpl.insertChildAt(InnerNodeImpl.java:118)
03-10 10:49:20.943: W/System.err(22584): at org.apache.harmony.xml.dom.InnerNodeImpl.appendChild(InnerNodeImpl.java:52)

XML 文档具有以下层次结构:

<?xml version="1.0" encoding="UTF-8"?>
<msg>
<header>
<method>Call</method>
</header>
</msg>

我正在尝试使用 replaceChild() 方法将元素 header 替换为另一个元素:

doc.replaceChild(header, (Element)doc.getElementsByTagName("header").item(0));

但我遇到了上述异常。因此,我跟踪异常以查看它被抛出的位置,这使我找到了 org.apache.harmony.xml.dom.InnerNodeImpl 类中的以下行:

public Node removeChild(Node oldChild) throws DOMException {

LeafNodeImpl oldChildImpl = (LeafNodeImpl) oldChild;
if (oldChildImpl.document != document) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, null);
}

if (oldChildImpl.parent != this) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, null); // This is where the Exception got thrown
}

int index = oldChildImpl.index;
children.remove(index);
oldChildImpl.parent = null;
refreshIndices(index);
return oldChild;

}

这意味着它无法将元素 header 识别为文档的子元素,这是不正确的,那么,我在这里遗漏了什么?!!

作为引用,以下是我在这个过程中使用的整个方法:

private void forming_and_sending_xml(String message, Element header){

Document doc = null;
try {
doc = loadXMLFromString(message);
} catch (Exception e) {
e.printStackTrace();
}
doc.getDocumentElement().normalize();
doc.replaceChild(header, (Element)doc.getElementsByTagName("header").item(0)); // this is where I got the Exception

}

更新

我改变了替换元素的方式,我使用 importNode 将节点添加到文档中,然后我将替换过程分离为(删除 ->添加),这使我能够修复所有与删除过程相关的问题,现在元素已成功删除,但文档不批准添加新元素,它会抛出与上述相同的异常。

我的新方法:

private void forming_and_sending_xml(String message, Element header){

Document doc = null;
try {
doc = loadXMLFromString(message);
} catch (Exception e) {
e.printStackTrace();
}
doc.getDocumentElement().normalize();
doc.importNode(header, true);
Element header_holder = (Element)doc.getElementsByTagName("header").item(0);
header_holder.getParentNode().removeChild(header_holder); // this removes the Element from the Doc succeffully
doc.getDocumentElement().appendChild(header); // this is where the Exception is got thrown now

}

最佳答案

我猜这里有两个错误:

  1. <header>元素必须导入到现有文档中(如评论中已讨论的那样),并且

  2. oldChild节点必须是上下文节点的直接子节点,而不是示例中的孙节点。替换

    doc.replaceChild(header, (Element)doc.getElementsByTagName("header").item(0)); 

    doc.getDoumentElement().
    replaceChild(doc.importNode(header, true),
    (Element)doc.getElementsByTagName("header").item(0));

关于java - appendChild 处的 DOMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com