题
我正在尝试添加“标题”元素,但我得到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"));
上面的行抛出错误:线程中的异常“main” org.w3c.dom.DOMException: NO_MODIFICATION_ALLOWED_ERR
:尝试修改不允许修改的对象。
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)
在myProject.Main.main(Main.java:48)
打破;
}
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);
其他提示
由于某种原因,父节点似乎是只读的。 使用以下命令克隆文档:
Document newDoc = doc.cloneNode(true);
将其设置为读写:
newDoc.setReadOnly(false,true);
// ^^^^ also sets children
然后做你的东西。 保存后我会返回新文件。
原始文件来自何处?
这就是问题的原因 - 在文档中阅读的代码正在构建一个只读文档。如果不知道你是如何阅读它的,那么很难弄清楚如何改变它。
我刚刚使用JDK 1.4.2-11对Windows进行了快速测试,我可以确认使用DocumentBuilderFactory(来自Reader的XML内容)不会创建只读文档。