MehtaJasmin
asked on
How do I merge two different XML document using JDOM
Hi,
I have two XML document as listed below:
1) (xmlDocA)
<GLogXMLElement>
<Location>
<TransactionCode>NP</Trans actionCode >
<LocationGid>
<Gid>
<Xid>Rockville</Xid>
</Gid>
</LocationGid>
<Address>
<AddressLines>
<SequenceNumber>2442</Sequ enceNumber >
<AddressLine>1221 E Otem Circle</AddressLine>
</AddressLines>
<City>Miami</City>
<ProvidenceCode>FL</Provid enceCode>
<PostalCode>91991</PostalC ode>
</Address>
</Location>
</GLogXMLElement>
2) (xmlDocB)
<Transmission>
<TransmissionHeader>
<UserName />
<Password />
</TransmissionHeader>
<TransmissionBody>
<!----- here goes GLogXMLElement XML element ---->
</TransmissionBody>
</Transmission>
I want to merge document 1) in to document 2) under <TransmissionBody> element.
Is it possible?
When I try to do that I get org.jdom.IllegalAddExcepti on: The Content already has an existing parent
I have two XML document as listed below:
1) (xmlDocA)
<GLogXMLElement>
<Location>
<TransactionCode>NP</Trans
<LocationGid>
<Gid>
<Xid>Rockville</Xid>
</Gid>
</LocationGid>
<Address>
<AddressLines>
<SequenceNumber>2442</Sequ
<AddressLine>1221 E Otem Circle</AddressLine>
</AddressLines>
<City>Miami</City>
<ProvidenceCode>FL</Provid
<PostalCode>91991</PostalC
</Address>
</Location>
</GLogXMLElement>
2) (xmlDocB)
<Transmission>
<TransmissionHeader>
<UserName />
<Password />
</TransmissionHeader>
<TransmissionBody>
<!----- here goes GLogXMLElement XML element ---->
</TransmissionBody>
</Transmission>
I want to merge document 1) in to document 2) under <TransmissionBody> element.
Is it possible?
When I try to do that I get org.jdom.IllegalAddExcepti
SAXBuilder saxBuilder = new SAXBuilder();
java.io.File xmlFile = new File("xmlDocA");
org.jdom.Document xmlDocumentA = saxBuilder.build(xmlFile);
xmlFile = new File("xmlDocB");
org.jdom.Document xmlDocumentB = saxBuilder.build(xmlFile);
Element rootA = xmlDocumentA.getRootElement();
List childrenDocA = rootA.getChildren();
Element rootB = xmlDocumentB.getRootElement();
Element childDocB = rootB.getChild("TransmissionBody");
childDocB.addContent(childrenDocA); ----------------- Exception at this line
XMLOutputter xmlOutPutter = new XMLOutputter(Format.getPrettyFormat());
xmlOutPutter.output(xmlDocumentB, System.out);
Try iterating the List and add the content yourself - ONLY after calling clone() on each Element
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The alternate solution is:
replace
childDocB.addContent(child renDocA);
to
childDocB.addContent(rootA .detach()) ;
replace
childDocB.addContent(child
to
childDocB.addContent(rootA