2013-02-19 110 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))); 
相关问题