2008-11-03 46 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