2013-02-19 116 views
0

這是我的問題:如何用另一個文檔替換一個XML元素?

我有一個源XML文件被解析爲DOM。我也有一個XML片段(如:<a>text1<b/></a>)。片段的「根」元素將始終與源DOM中的元素(同名)匹配。我可以用這個替換DOM的節點嗎?

首先,我想到的東西是將字符串片段解析爲DOM。然後,我嘗試使用replaceChild()方法,但是我錯誤地使用了它,或者它只能應用於已存在於同一DOM中的節點。那麼有人可以證明我怎麼能做到這一點?

回答

1

您可能需要首先調用getParentNode(),然後針對您擁有的父節點調用replaceChild()。

+0

謝謝你,你是對的!我誤解了API並試圖在文檔根目錄上應用該方法。現在按預期工作。此外,我不得不使用importNode()爲了從另一個文檔的片段得到所需的。 – user2089117 2013-02-20 20:48:47

0
//Importing template node to the target document(this solves wrong_DOCUMENT_ERR:) 
Node importedTemplateChildNode = targetDoc.importNode(templateChildNode, true); 

// Replace target child node with the template node 
targetParentNode.replaceChild(importedTemplateChildNode, targetChildnode);  

Transformer tranFac = TransformerFactory.newInstance().newTransformer(); 
tranFac.transform(new DOMSource(targetDoc), new StreamResult(new FileWriter(targetXmlFile))); 
相關問題