本質上,我從文件(數據庫)創建XML文檔,然後將另一個解析的XML文件(具有更新的信息)與原始數據庫進行比較,然後將新的信息寫入數據庫。將子元素添加到元素java(DOM)
我正在使用java的org.w3c.dom。
經過大量的掙扎,我決定只創建一個新文檔對象,並從那裏寫從oldDocument和新建文檔的人我在快樂的比較要素
的XML文檔中的格式如下:
<Log>
<File name="something.c">
<Warning file="something.c" line="101" column="23"/>
<Warning file="something.c" line="505" column="71" />
</File>
</Log>
作爲一個例子。
我將如何去添加一個新的「警告」元素到「文件」而不會讓人討厭「org.w3c.dom.DOMException:WRONG_DOCUMENT_ERR:一個節點用於不同於創建的文檔它。」例外?
切割下來,我有類似的東西:
public static Document update(Element databaseRoot, Element newRoot){
Document doc = db.newDocument(); // DocumentBuilder defined previously
Element baseRoot = doc.createElement("Log");
//for each file i have:
Element newFileRoot = doc.createElement("File");
//some for loop that parses through each 'file' and looks at the warnings
//when i come to a new warning to add to the Document:
NodeList newWarnings = newFileToCompare.getChildNodes(); //newFileToCompare comes from the newRoot element
for (int m = 0; m < newWarnings.getLength(); m++){
if(newWarnings.item(m).getNodeType() == Node.ELEMENT_NODE){
Element newWarning = (Element)newWarnings.item(m);
Element newWarningRoot = (Element)newWarning.cloneNode(false);
newFileRoot.appendChild(doc.importNode(newWarningRoot,true)); // this is what crashes
}
}
// for new files i have this which works:
newFileRoot = (Element)newFiles.item(i).cloneNode(true);
baseRoot.appendChild(doc.importNode(newFileRoot,true));
doc.appendChild(baseRoot);
return doc;
}
任何想法?我正在撞牆。第一次這樣做。
你試過了採用方法嗎?看到這個帖子它看起來像你的:http://stackoverflow.com/questions/873247/how-do-i-copy-dom-nodes-from-one-document-to-another-in-java –
@fabient如果你看看我正在做的代碼......並且它不起作用。 newFileRoot是doc.getDocumentElement()。也採用元素不存在。 – Natalie
是的在Java中它是imporNode(對不起,方法名稱改爲javascript)方法。事實上,你不能拿一個Dom元素的樹,並把它們放在一個新的Dom文檔中。您需要在新文檔中導入這些節點。 –