Seva's notes

Wisdom, Awareness, Responsibility :)

Archive for June 2008

Copying nodes between XML documents with Java DOM

with 7 comments

Today I had an atomic task of creating a more convenient way to copy nodes from one XML document to another with Java’s DOM implementation. Googling did not help me much in it, so I will share the solution here in case someone would be challenged too.

So, imagine you have multiple XML documents like this:

        <node attribute="value" />

…, another one like this:

<storage><sections /></storage>

… and you wish to read the multilple documents and to put the <section> nodes into the <sections> node of the second one respecting all the structure.

To do that you should:

1. Create the XML document builder:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

2. Get the <sections> node of the target file:

File target;
Document targetDom = builder.parse(new InputSource(new FileReader(target));
Node targetSections = targetDom.getElementsByTagName("sections").item(0);
// TODO this is not the best way to use that.
// I advice XPath instead.

3. Iterate over the source files and get the <section> nodes:

File[] sources;
for (File source : sources) {
    Node sourceSection = builder.parse(new InputSource(new FileReader(source))
    // continued inside

4. Copy the node into the target document:

// 'true' means we want to clone children too

5. Write the target back to the file:

    new DOMSource(targetDom),
    new StreamResult(new FileWriter(target))

That’s it. Note, this code lacks error handling and probably won’t work directly after copy-paste, but just shows you the usage of the classes.

Written by Seva

2008-06-26 (June 26) at 03:22:17