This helps in
merging xml fragment from one xml to another, below the tag
specified.
Problem this asset
addresses
1. copy xml
fragment from one xml to another
2. place the
copied fragment below the tag mentioned
3. read xml
document which was stored in a string
Sample code used
below is to merge 2 document as follows,
doc
NEW ............ 0
doc1
NEW ................. 1 NEW .................2 NEW .................3
import java.io.File; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlParse { public static void main(String[] args) { try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setIgnoringComments(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new File("D:\Test\src\test.xml")); Document doc1 = builder.parse(new File("D:\Test\src\test1.xml")); /***** Read xml document which is stored in a string *******/ /*String inputxml ="<?xml version="1.0" encoding="UTF-8" standalone="no"?><Customer><names><firstName>fName</firstName><lastName>lName</lastName><middleName>nName</middleName></Customer>"; InputStream is = new ReaderInputStream(new StringReader(inputxml)); Document doc = builder.parse(is);*/ NodeList nodes = doc.getElementsByTagName("facility"); NodeList nodes1 = doc1.getElementsByTagName("facility"); for(int i=2;i<nodes1.getLength();i=i+2){ Node n=doc.importNode(nodes1.item(i), true); nodes.item(0).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); String xmlOutput = result.getWriter().toString(); System.out.println(xmlOutput); } catch (Exception e) { System.out.println(e); } } }
Output format:
NEW ................. 0 NEW .................2 NEW .................3
Needed Jar :
commons-io-1.4.jar