I would like to concatenate two org.w3c.dom.Document s, I have something like this:
Document finalDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
Document document1 = createDocumentOne();
Document document2 = createDocumentTwo();
// This didn't work
changeFileDocument.appendChild(document1);
changeFileDocument.appendChild(document2);
The format of the document1 and document2 is something like this:
<headerTag>
<tag1>value</tag1>
</headerTag>
And what I want is, at the end, a Document like this:
<headerTag>
<tag1>valueForDocument1</tag1>
</headerTag>
<headerTag>
<tag1>valueForDocument2</tag1>
</headerTag>
I think that you cannot do this, because they should have a common parent. If so, I would like to create that "fake" parent, concatenate the files, but then only recover the List of elements headerTag
How can I do this?
As you say, you need to have a single root node - and you need to import the other documents. For example:
Element root = finalDocument.createElement("root");
finalDocument.appendChild(root);
root.appendChild(
finalDocument.importNode(document1.getDocumentElement(), true));
root.appendChild(
finalDocument.importNode(document2.getDocumentElement(), true));
See more on this question at Stackoverflow