I wrote a program (I'm using JDK 11) to format an XML string; however, I want my program to contract empty elements. For example: <element></element>
should become <element/>
. I have written the below code which does not work:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
transformer.transform(new DOMSource(unformattedXml),new StreamResult(stringWriter));
return stringWriter.toString();
How can I contract the empty elements?