In the previous post we have discussed about how we can collect tags by name in two xmls.
NodeList fNodes, sNodes;fNodes = fMsg.getElementsByTagName("person");sNodes = sMsg.getElementsByTagName("person");
Now we have fNodes and sNodes variables with elements by tag inside. We'll append the elements of one xml to the other xml.
for (int i = 0; i < sNodes.getLength(); i = i + 1) { Node n = (Node) fMsg.importNode(sNodes.item(i), true); fNodes.item(i).getParentNode().appendChild(n);}
Okay....!!!!!Everything is okay now.All we have to do is get the output from above implementation.First we'll create a StringWriter object and parse the fMsg object to it.Here we have to use the Transformer object in order to build the new xml.
StringWriter buf = new StringWriter();Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");transformer.transform(new DOMSource(fMsg), new StreamResult(buf));<\br>String newBuf = buf.toString();System.out.println(newBuf);
First we'll create an Arraylist of Inputstreams.
ArrayList<InputStream> messages = new ArrayList<>();collectedMessages.forEach(msg -> { InputStream = = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8)); messages.add(inputStream);});
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();domFactory.setIgnoringComments(true);DocumentBuilder builder = domFactory.newDocumentBuilder();
Document fMsg, sMsg;NodeList fNodes, sNodes;
while (messages.size() > 1) {
byte[] b = new byte[1024];
fMsg = builder.parse(messages.get(0));
sMsg = builder.parse(messages.get(1));
fNodes = fMsg.getElementsByTagName(mergePath);
sNodes = sMsg.getElementsByTagName(mergePath);
for (int i = 0; i < sNodes.getLength(); i = i + 1) {
Node n = (Node) fMsg.importNode(sNodes.item(i), true);
fNodes.item(i).getParentNode().appendChild(n);
}
StringWriter buf = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.transform(new DOMSource(fMsg), new StreamResult(buf));
String rootlessBuf = buf.toString();
b = rootlessBuf.getBytes(StandardCharsets.UTF_8);
InputStream xmlOutput = new ByteArrayInputStream(b);
messages.remove(0);
messages.remove(0);
messages.add(0, xmlOutput);
}
At the end we have messages array list which contains only one element.So we can convert that inputstream to string and get the output.
Comments
Post a Comment