Move xml nodes from one document to another

K

kapiladhanvi

Hi Everyone,

I need to move nodes in a XML document ( doc1 ) in namespace A to
another XML document (doc2) in namespace B.

I have tried adoptNode() as shown below but the nodes in doc2 still
have namespace URI for the nodes as namespace A. Below is the code
( this is just to provide a gist of what I am doing, not exactly
compilable code here ) -

function Document swapNodesAndReturnNewDoc( String namespaceB,
Document doc1 )
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc2 = db.newDocument();
doc2.setDocumentURI( namespaceB );

Element root = doc1.getDocumentElement();

Node clonedNode = root.cloneNode(true);
doc2.adoptNode( clonedNode );
doc2.appendChild( clonedNode );

return doc2;
}

I have tried searching google and couldn't help around this. I have
tried importNode() too earlier and had the same results.. I would be
really glad to get any pointers as to where I might be going wrong.

Thanks
Dhanvi
 
M

Mike Schilling

Hi Everyone,

I need to move nodes in a XML document ( doc1 ) in namespace A to
another XML document (doc2) in namespace B.

I have tried adoptNode() as shown below but the nodes in doc2 still
have namespace URI for the nodes as namespace A.

Yes. Neither importNode() nor adoptNode() will change the fully
qualified name of the node. To change it, you'll have to create new
instances of Element. Note that Document.setDocumentURI() sets the
location at which the document is found, not any element's namespace.
 
A

Arne Vajhøj

I need to move nodes in a XML document ( doc1 ) in namespace A to
another XML document (doc2) in namespace B.

I have tried adoptNode() as shown below but the nodes in doc2 still
have namespace URI for the nodes as namespace A. Below is the code
( this is just to provide a gist of what I am doing, not exactly
compilable code here ) -
I have tried searching google and couldn't help around this. I have
tried importNode() too earlier and had the same results.. I would be
really glad to get any pointers as to where I might be going wrong.

A different namespace means a completely different node.

I think you will need to manually create a new element
from the old element.

And if there are sub element you will need to do it
recursively.

Arne
 

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

Staff online

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top