2008-11-03 18 views
3

我想添加一个“标题”元素,但我得到一个错误NO_MODIFICATION_ALLOWED_ERR ...如何在Java中添加XML元素1.4

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) 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> 

回答

2

不确定是否这是原因,但检查您的DOM实现是否验证对DOM的所有更改。因为在你的代码,

nextNode.appendChild(doc.createTextNode("title")); 

将尝试创建一个文本节点作为map元素的儿童和DITA地图不允许。请尝试使用

Element title = doc.createElement("title"); 
title.appendChild(doc.createTextNode("title content")) 
nextNode.appendChild(title); 
0

出于某种原因,父节点似乎是只读的。 使用克隆文件:

Document newDoc = doc.cloneNode(true); 

将其设置为通过读写:

newDoc.setReadOnly(false,true); 
//      ^^^^ also sets children 

然后做你的东西。 虽然保存后我会返回新文档。

+0

Node和Document在1.4中都没有setReadOnly属性。你能帮我解决这个问题吗? – joe 2008-11-03 22:26:47

0

原始文件来自哪里?

这是问题的原因 - 在文档中读取的代码正在构造一个只读文档。如果不知道如何阅读它,就很难找出如何改变它。

我刚刚在Windows上用JDK 1.4.2-11做了一个快速测试,我可以确认使用DocumentBuilderFactory(带有来自Reader的XML内容)不会创建只读文档。

+0

我更新了代码,以便显示我从哪里得到它。 – joe 2008-11-05 16:27:39

+0

**更新了代码示例以显示 – joe 2008-11-05 17:23:16