Take the 2-minute tour ×

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.

        <name>Student Name<name>
        <address>somewhere 1<address>
share|improve this question
What are you using to process XML (parsers, frameworks etc.)? –  Sean Patrick Floyd May 12 '11 at 12:37
You can either parse the xml or use xptath to get the section that you are interested in. –  Kaj May 12 '11 at 12:42

1 Answer 1

up vote 8 down vote accepted

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);

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.

share|improve this answer
Thanx for the info it is what i need –  Eve May 12 '11 at 13:39
what exactly is "findWhereYouWantToCopyStuffTo" a methode? –  Eve May 12 '11 at 13:59
with out you being a little bit more specific about where you want to copy which nodes to, can't answer that :).. I'm assuming that you are copying the nodes to another document.. so findWhereYouWantToCopyStuffTo() should find the location in the target document and return it. Note the above can also be used to copy nodes within the same document. –  Gareth Davis May 12 '11 at 15:01

Your Answer


