Print an empty XML element as an opening tag, a closing tag

Is there a way to print blank elements like <tag></tag> and not <tag /> using org.w3c.dom? I am modifying XML files that you need to distinguish from older versions to view.

If this helps, the code that writes the XML to a file:

 TransformerFactory t = TransformerFactory.newInstance(); Transformer transformer = t.newTransformer(); DOMSource source = new DOMSource(doc); StringWriter xml = new StringWriter(); StreamResult result = new StreamResult(xml); transformer.transform(source, result); File f = new File("output.xml"); FileWriter writer = new FileWriter(f); BufferedWriter out = new BufferedWriter(writer); out.write(xml.toString()); out.close(); 

Thanks.

+4
source share
2 answers

Perhaps you should consider converting the old and new XML file to Canonical XML - http://en.wikipedia.org/wiki/Canonical_XML - before comparing them with, for example, diff.

James Clark has a little Java program to do this at http://www.jclark.com/xml/

+3
source

I assume that the empty elements are actually ELEMENT_NODE without any child elements in the document. Try adding empty node text instead. This can trick the author into believing that there is node text there, so he will write it as if it were one. But node text does not output anything because it is an empty string.

Calling this method with a document, since both parameters should do the trick:

 private static void fillEmptyElementsWithEmptyTextNodes( final Document doc, final Node root) { final NodeList children = root.getChildNodes(); if (root.getType() == Node.ELEMENT_NODE && children.getLength() == 0) { root.appendChild(doc.createTextNode("")); } // Recurse to children. for(int i = 0; i < children.getLength(); ++i) { final Node child = children.item(i); fillEmptyElementsWithEmptyTextNodes(doc, child); } } 
+1
source

Source: https://habr.com/ru/post/1314491/


All Articles