Howto: Extract Node/sub-tree of a Document and form a new XMLDocument

C

Casper B

As the topic says, I am wondering how (in Java) I can extract a sub-tree
of a org.w3c.dom.Document and form a brand new one. I use Oracle's
XMLDocument implementation and have been playing around with
DocumentFragment etc. but somehow I always end up creating only the
single node and not its sub-nodes.

/Casper
 
S

Stanimir Stamenkov

/Casper B/:
As the topic says, I am wondering how (in Java) I can extract a sub-tree
of a org.w3c.dom.Document and form a brand new one. I use Oracle's
XMLDocument implementation and have been playing around with
DocumentFragment etc. but somehow I always end up creating only the
single node and not its sub-nodes.

You probably need the 'Document.importNode' method:

http://www.w3.org/TR/DOM-Level-2-Core/core.html#Core-Document-importNode
http://java.sun.com/j2se/1.4.2/docs...nt.html#importNode(org.w3c.dom.Node, boolean)

Notice the 'deep' parameter:
deep - If true, recursively import the subtree under the specified
node; if false, import only the node itself, as explained above.
This has no effect on Attr, EntityReference, and Notation nodes.

Something like:

Document doc1;
Element elem1; // element from 'doc1'

Document doc2;
Element elem2; // element from 'doc2'

// perform a deep copy of 'elem1' from 'doc1' adding
// it as child of 'elem2' from 'doc2'
elem2.appendChild(doc2.importNode(elem1, true));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top