JDOM Transformer - don't contract empty elements

I'm using JDOM 2.0.6 to transform an XSLT into an HTML, but I'm coming across the following problem - sometimes the data should be empty, that is, I'll have in my XSLT the following:

<div class="someclass"><xsl:value-of select="somevalue"/></div>

and when somevalue is empty, the output I get is:

<div class="someclass"/>

which may be perfectly valid XML, but is not valid HTML, and causes problems when displaying the resulting page. Similar problems occur for <span> or <script> tags.

So my question is - how can I tell JDOM not to contract empty elements, and leave them as <div></div>?

I suspect the problem is not in the actual XSLTTransformer, but later when using JDOM to write to html. Here is the code I use:

XMLOutputter htmlout = new XMLOutputter(Format.getPrettyFormat());

Document htmlDoc = transformer.transform(model);
htmlDoc.setDocType(new DocType("html"));

try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outHtml), "UTF-8")) {
    htmlout.output(htmlDoc, osw);

Currently the proposed solution of adding a zero-width space works for me, but I'm interested to know if there is a way to tell JDOM to treat the document as an HTML (be it in the transform stage or the output stage, but I'm guessing the problem lies in the output stage).

You can use a zero-width-space between the elements. This doesn't affect the HTML output, but keeps the open-close-tags separated because they have a non-empty content.

<div class="someclass">&#8203;<xsl:value-of select="somevalue"/></div>

Downside is: the tag is not really empty anymore. That would matter if your output would be XML. But for HTML - which is probably the last stage of processing - it should not matter.

In your case, the XML transform is happening directly to a file/stream, and it is no longer in the control of JDOM.

In JDOM, you can select whether the output from the JDOM document has expanded, or not-expanded output for empty elements. Typically, people have output from JDOM like:

XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(document, System.out);

You can modify the output format, though, and expand the empty elements

Format expanded = Format.getPrettyFormat().setExpandEmptyElements(true);
XMLOutputter xout = new XMLOutputter(expanded);
xout.output(document, System.out);

If you 'recover' (assuming it is valid XHTML?) the XSLT transformed xml as a new JDOM document you can output the result with expanded empty elements.

If you want to transform to a HTML file then consider to use Jaxp Transformer with a JDOMSource and a StreamResult, then the Transformer will serialize the transformation result as HTML if the output method is html (either as set in your code or as done with a no-namespace root element named html.