Merging multiple xmls using Java (Part-1)

In the previous post we have completed our implementation on the "xml splitter". So in this post we'll discuss about how we can merge multiple xmls using Java.  Assume you have following xmls.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>     
<person>
    <id>person0</id>
    <name>name0</name>
    <age>age0</age>
 </person>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <id>person1</id>
    <name>name1</name>
    <age>age1</age>
 </person>

When the xpath is given as //person you want these two xmls to be merged to one xml from <person></person> tags.The final output should look like this.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>          
<persons>
     <person>
         <id>person0</id>
         <name>name0</name>
         <age>age0</age>
     </person>
     <person>
         <id>person1</id>
         <name>name1</name>
         <age>age1</age>
     </person>
</persons>

Let's see how we can do this using Java. As mentioned in the previous posts we'll first convert these two xml strings to inputstreams.

InputStream is1 = new ByteArrayInputStream(xmlstring1.getBytes(StandardCharsets.UTF_8));
InputStream is2 = new ByteArrayInputStream(xmlstring2.getBytes(StandardCharsets.UTF_8));

Next we need to initialize the parser to parse these two inputstreams.

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();

We have discussed about domFactory object methods in the previous posts.You can apply those settings here and make an XmlErrorHandler class.But the above settings are enough for a sample test.Let's parse two inputstreams now.

Document fMsg, sMsg;
fMsg = builder.parse(is1);
sMsg = builder.parse(is2);

Now we have Document objects for two xmls. Let's initialize two NodeList objects and collect elements by <person></person> tags.

NodeList fNodes, sNodes;
fNodes = fMsg.getElementsByTagName("person");
sNodes = sMsg.getElementsByTagName("person");

Alright...!Now we have everything we need.We just have to append elements of one xml to the other xml. We'll talk about it in next post.

Comments