Link to home
Start Free TrialLog in
Avatar of MehtaJasmin
MehtaJasminFlag for United States of America

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</TransactionCode>
      <LocationGid>
         <Gid>
            <Xid>Rockville</Xid>
         </Gid>
      </LocationGid>
      <Address>
         <AddressLines>
            <SequenceNumber>2442</SequenceNumber>
            <AddressLine>1221 E Otem Circle</AddressLine>
         </AddressLines>
         <City>Miami</City>
         <ProvidenceCode>FL</ProvidenceCode>
         <PostalCode>91991</PostalCode>
      </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.IllegalAddException: The Content already has an existing parent

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

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try iterating the List and add the content yourself - ONLY after calling clone() on each Element
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MehtaJasmin

ASKER

The alternate solution is:

replace

childDocB.addContent(childrenDocA);                            

to

childDocB.addContent(rootA.detach());