5

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@email.com<email>
        <address>somewhere 1<address>
        <postalcode>123456<postalcode>
    <contactinfo>
<body>
<header>
Eve
  • 514
  • 3
  • 12
  • 23

1 Answers1

11

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.

Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
  • what exactly is "findWhereYouWantToCopyStuffTo" a methode? – Eve May 12 '11 at 13:59
  • 1
    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