Merging xml file using java NodeList

steven72555

New Member
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:\[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");\[/code\]File1.xml\[code\] <company> <staff> <name>john</name> <phone>465456433</phone> <email>gmail1</email> </staff> </company>\[/code\]File2.xml\[code\] <company> <staff> <area>area1</area> <city>city1</city> </staff> </company>\[/code\]Current output:\[code\] <company> <staff> <name>john</name> <phone>465456433</phone> <email>gmail1</email> </staff> <staff> <area>area1</area> <city>city1</city> </staff> </company>\[/code\]Expected Output:\[code\] <company> <staff> <name>john</name> <phone>465456433</phone> <email>gmail1</email> <area>area1</area> <city>city1</city> </staff> </company>\[/code\]
 
Back
Top