Copy certain nodes with Java

Eve picture Eve · May 12, 2011 · Viewed 8.1k times · Source

I'm trying to read/copy a certain part of a xml document in JAVA and then save this part as a new xml document. So like in de example below you see studentinfo and contact info, I just want to select studentinfo and copy the entire area so nodes and elements. I can only find info about selecting only the element or only the nodes.

So help would be appreciated, thank you.

<header>
<body>
    <studentinfo>
        <name>Student Name<name>
        <studentid>0987654321<studentid>
        <Location>USA<Location>
    <studentinfo>
    <contactinfo>
        <email>[email protected]<email>
        <address>somewhere 1<address>
        <postalcode>123456<postalcode>
    <contactinfo>
<body>
<header>

Answer

Gareth Davis picture Gareth Davis · May 12, 2011

I'm going to make a big assumption, and that is that you are using the org.w3c.dom.Document api.

This is a two step process:

Document doc = parse(xmlSource);

Document targetDoc = openTargetDoc();
Node copyTo = findWhereYouWantToCopyStuffTo(targetDoc);

// Find the node or nodes to want to copy.. could use XPath or some other search
NodeList studentinfoList = doc.getElementsByTagName("studentinfo");

// for each found... make a copy (via importNode) and attach to some point in the target doc
for( int i = 0; i < studnetinfoList.getLength(); i ++ ){
    Node n = studentinfoList.item(i);
    Node copyOfn = targetDoc.importNode(n,true);
    copyTo.appendChild(copyOfn);
}

If this isn't what you are looking for, you might need to add a bit more detail of what you wish to copy and where to, using what api etc.