Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging xml file using java NodeList

Tags:

I'm trying to merge two xml files as shown below but i can't able to get the desired output please help me thank you

Java code:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();   
domFactory.setIgnoringComments(true);  
DocumentBuilder builder = domFactory.newDocumentBuilder();   
Document doc = builder.parse(new File("file1.xml"));   
Document doc1 = builder.parse(new File("file2.xml"));   

NodeList nodes = doc.getElementsByTagName("staff");  

NodeList nodes1 = doc1.getElementsByTagName("staff");

for(int i=0;i<nodes1.getLength();i=i+1){  

Node n= (Node) doc.importNode(nodes1.item(i), true);  
nodes.item(i).getParentNode().appendChild(n);

}  

Transformer transformer = TransformerFactory.newInstance().newTransformer();  
transformer.setOutputProperty(OutputKeys.INDENT, "yes");  

StreamResult result = new StreamResult(new StringWriter());  
DOMSource source = new DOMSource(doc);  
transformer.transform(source, result);  
Writer output = null;
output = new BufferedWriter(new FileWriter("mergedxml.xml"));

String xmlOutput = result.getWriter().toString();  
output.write(xmlOutput);
output.close();
System.out.println("merge complete");

File1.xml

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
        </staff>
    </company>

File2.xml

    <company>
        <staff>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>

Current output:

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
        </staff>
        <staff>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>

Expected Output:

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>