我正在尝试添加“标题”元素,但收到 NO_MODIFICATION_ALLOWED_ERR 错误...
private static void saveDoc(String f) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
// create DOMSource for source XML document
DOMSource xmlSource = new DOMSource(doc);
Node nextNode = xmlSource.getNode().getFirstChild();
while (nextNode != null) {
System.out.print("\n node name: " + nextNode.getNodeName() + "\n");
if (nextNode.getNodeName().equals("map")) {
nextNode.appendChild(doc.createElement("title"));
上面的行抛出错误:
Exception in thread "main" org.w3c.dom.DOMException:
NO_MODIFICATION_ALLOWED_ERR
: An attempt is made to modify an object where modifications are not allowed. at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source) at myProject.Main.saveDoc(Main.java:171) at myProject.Main.main(Main.java:48)
break;
}
nextNode = nextNode.getNextSibling();
}
}
我的 xml 文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<?dctm xml_app="LOPackage"?>
<!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd">
<map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)">
<topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/>
<topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/>
<topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/>
</map>
最佳答案
不确定是否是这个原因,但请检查您的 DOM 实现是否验证了对 DOM 的所有更改。因为在你的代码中,
nextNode.appendChild(doc.createTextNode("title"));
将尝试创建一个文本节点作为 map
元素的子元素,而 DITA Map 不允许这样做。相反,尝试
Element title = doc.createElement("title");
title.appendChild(doc.createTextNode("title content"))
nextNode.appendChild(title);
关于java - 如何在 Java 1.4 中添加 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/260122/