Java XMLSerializer avoids complex empty elements

I have 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 need to console this:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <text/>
</root>

But I would like to get the following:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <text></text>
</root>

Does anyone know how to install XMLSerializer to avoid complex empty elements? Thank.

+3
source share
2 answers

I had the same problem with XMLSerializer that did not allow customization of empty tags. My solution was to extend the XMLSerializer source code and override the serializeElement method:

I copied the source code and changed the final part of the print:

protected void serializeElement (Elem) throws an IOException ...

if (isSelfClosingElement(elem))
    _printer.printText("/>");
else
_printer.printText("></" + elem.getTagName() + ">");

where isSelfClosingElement contains a list of self-closing elements

: printAttribute() printNamespaceAttr(), , .

+1

: , . XMLSerializer ​​.

: serializer.serialize(root), BaseMarkupSerializer serialize (Element). node, .

node, XMLSerializer serializeElement (Element):

// If element has children, then serialize them, otherwise
// serialize en empty tag.       
if (elem.hasChildNodes()) {
    //... irrelevant code...
    endElementIO( null, null, tagName );
} else {
    //... irrelevant code...
    _printer.printText( "/>" ); // <------ HARDCODED, NON-CONFIGURABLE
    //... irrelevant code...
}

: , ( ).

: XMLSerializer , , . :

_printer.printText( "/>" );

_printer.printText( "</" );
_printer.printText( elem.getTagName() );
_printer.printText( ">" );

: , , . , / .

+3

All Articles