Seva's notes

Wisdom, Awareness, Responsibility :)

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:

<document>
    <section>
        <node attribute="value" />
    </section>
</document>

…, 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))
        .getElementsByTagName("section").item(0);
    // continued inside
}

4. Copy the node into the target document:

targetSections.appendChild(targetDom.adoptNode(sourceSection.cloneNode(true)));
// 'true' means we want to clone children too

5. Write the target back to the file:

TransformerFactory.newInstance().newTransformer().transform(
    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

7 Responses

Subscribe to comments with RSS.

  1. Thanks. it helped me a lot.

    Pavan

    2010-09-17 (September 17) at 11:33:52

    • It would be much useful if you attached complete listing, e.g. you have sourceSection and targetSections that are never used (as it seems from the existing listings).

      best regards

      Lukasz 'Severiaan' Grela

      2011-09-23 (September 23) at 10:29:02

  2. Thakns Man 🙂 It helped me a lot too …

    indra preet

    2012-06-14 (June 14) at 12:48:24

  3. This is really good it helped me.

    suresh

    2012-08-11 (August 11) at 09:25:08

  4. I got answers on my questions! This article is useful, thank you.

    Karinka

    2013-04-04 (April 4) at 06:54:02

  5. Thanks a lot. it helped me.
    I tried it before I read your post in almost the same way; the thing I did not know was the call of method adoptNode() on the target document. That is the important point, and a bit tricky, I think. The rest seems straight-forward.
    Thanks again!

    MatEngel

    2014-08-27 (August 27) at 12:00:21


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: