Skip to content

Instantly share code, notes, and snippets.

@sfat
Last active March 6, 2019 09:21
Show Gist options
  • Save sfat/5c3129e567b26dcb7f8b8e06222ee44d to your computer and use it in GitHub Desktop.
Save sfat/5c3129e567b26dcb7f8b8e06222ee44d to your computer and use it in GitHub Desktop.
public class ContentDuplicator {
public static void main(String[] args)
throws IOException, SAXException, ParserConfigurationException, TransformerException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<note>\n"
+ " <content>\n"
+ " <ele> something </ele>\n"
+ " <tic> something else </tic>\n"
+ " </content>\n"
+ "\n"
+ " <tac>data</tac>\n"
+ " <toc>data2</toc>\n"
+ "</note>";
Document document = parseXml(xml);
Node tacNode = document.getElementsByTagName("tac").item(0);
Node noteNode = document.getElementsByTagName("note").item(0);
NodeList contentNode = document.getElementsByTagName("content");
Node newNode = contentNode.item(0).cloneNode(true);
noteNode.insertBefore(newNode, tacNode);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String output = writer.getBuffer().toString();
System.out.println(output);
}
private static Document parseXml(String file)
throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream(file.getBytes(StandardCharsets.UTF_8));
return builder.parse(input);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<note>
<content>
<ele> something </ele>
<tic> something else </tic>
</content>
<tac>data</tac>
<toc>data2</toc>
</note>
<content>
<ele> something </ele>
<tic> something else </tic>
</content>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment