我试图通过替换XML文档中的某些元素来使用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>我试图使用header方法将元素replaceChild()替换为另一个元素:
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;
}这意味着它不能将元素头识别为不正确的文档的子元素,所以,我在这里遗漏了什么?!!
作为参考,以下是我在这个过程中使用的整个方法:
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将节点添加到文档中,然后将替换过程分离为(remove -> add),这使我能够修复与删除过程相关的所有问题,现在元素正在成功删除,但文档不批准添加新元素,它引发的异常与上面提到的相同。
我的新方法:
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
}发布于 2016-03-10 11:42:03
我想这里有两个错误:
<header>元素导入到现有文档中(正如注释中已经讨论过的那样),以及oldChild节点必须是上下文节点的直接子节点,而不是示例中的外孙。替换
(Element)doc.getElementsByTagName("header").item(0));(标头,doc.replaceChild)
使用
doc.getDoumentElement()。(Element)doc.getElementsByTagName("header").item(0));replaceChild(doc.importNode(标头,真))https://stackoverflow.com/questions/35912595
复制相似问题