[英]Adding sub-element to element java (DOM)
本質上,我是從文件(數據庫)創建XML文檔,然后將另一個解析的XML文件(具有更新的信息)與原始數據庫進行比較,然后將新信息寫入數據庫。
我正在使用Java的org.w3c.dom。
經過很多努力之后,我決定只創建一個新的Document對象,並在其中比較元素的oldDocument和newDocument中從那里寫入。
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;
}
有任何想法嗎? 我的頭撞在牆上。 第一次這樣做。
通過調試器,我驗證了文檔所有者是正確的。 使用node.getOwnerDocument(),我發現在創建新文件時,newFileRoot早已連接到錯誤的文檔,因此我進行了更改
Element newFileRoot = (Element)pastFileToFind.cloneNode(false);
至
Element newFileRoot = (Element)doc.importNode(pastFileToFind.cloneNode(false),true);
從后來以后,當我嘗試將newWarningRoot添加到newFileRoot時,它們具有不同的Documents(newWarningRoot是正確的,但newFileRoot連接到錯誤的文檔)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.