I’ve got this code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
Document xmldoc = impl.createDocument(null, null, null);
Element root = xmldoc.createElement("root");
Element textElement = xmldoc.createElement("text");
Text textNode = xmldoc.createTextNode("");
root.appendChild(textElement);
textElement.appendChild(textNode);
OutputFormat of = new OutputFormat("XML","UTF-8",true);
of.setIndent(1);
of.setIndenting(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
XMLSerializer serializer = new XMLSerializer(stream, of);
// As a DOM Serializer
serializer.asDOMSerializer();
serializer.serialize(root);
System.out.println(stream.toString());
I get to console this:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<text/>
</root>
But, I’d like to get this:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<text></text>
</root>
Does anybody know, how to set the XMLSerializer to avoid Complex Empty Elements?
Thanks.
I had the same problem with XMLSerializer not allowing rendering customization of empty tags. My solution was to extend the original XMLSerializer code and override the serializeElement method:
I have copied the original code and changed the closing printing part:
protected void serializeElement(Element elem) throws IOException
…
where isSelfClosingElement holds a list of self closing elements
NOTE: additionally you need to copy the printAttribute() and printNamespaceAttr() method as it is marked private instead of protected.