Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to merge two XML's with JDOM?

843834Oct 7 2009 — edited Oct 7 2009
How to merge two xmls's using jdom? like:

is there a way to add the complete content one xml into the parent node of another xml?
//in.xml

<?xml version="1.0"?>
<people>
<person>
  <name>ABC</name>
  <email>abc@abc.com</email>
</person>
</people>

//out.xml
<?xml version="1.0"?>
<address>
<city> abccounty</city>
<state> abcstate</state>
</address>

Merged XML:

<?xml version="1.0"?>
<people>
<person>
  <name>xyz</name>
  <email>abc@abc.com</email>
</person>

<address>
<city> abccounty</city>
<state> abcstate</state>
</address>

</people>


import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class MergeXMLS {

	public static void main(String[] args) {
		
		try{
		    SAXBuilder builder = new SAXBuilder();
		    Document books = builder.build("D:/in.xml");
		    Document onebook = builder.build("D:/out.xml");
		    Element root = books.getRootElement();
		    List rows = root.getChildren();
		    
		    for (int i = 0; i < rows.size(); i++) {
		        Element row = (Element) rows.get(i);
		        onebook.getRootElement().addContent(row.detach());
		        System.out.println(row.getName());
		    }
		    new XMLOutputter(Format.getPrettyFormat()).output(onebook, System.out);
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 4 2009
Added on Oct 7 2009
3 comments
1,792 views