Prevent empty xml elements convert to self-closing elements

I am using the Xerces library to write XML in a document. To do this, I use the OutputFormat class passing an OutputFormat object to the XMLSerializer. But all my empty xml elements are converted to self-closing xml elements.

I want it:

<Company Name="Dummy">
</Company>

      

But its approaching like

<Company Name="Dummy" />

      

I've tried the code below:

try {
    //print
    OutputFormat format = new OutputFormat(dom,"iso-8859-1",true);          
    //to generate output to console use this serializer

    XMLSerializer serializer = new XMLSerializer(System.out, format);           
    serializer.serialize(dom);

} catch(IOException ie) {
        ie.printStackTrace();
}

      

Can someone help me on this.

Thank,

+3


source to share


2 answers


Most serializers that I know of don't allow you to choose whether or not to use empty element tags in the output, for the simple reason that no sane consumer of XML should care if they are used or not. If you care and not crazy, this will help explain why you care.



+3


source


If you would like to use other APIs to solve the problem, try this:



import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stax.StAXResult;

import org.w3c.dom.Document;

public class XmlWritter {

    public static void main(String[] args) throws Exception {
        Document doc = ...
        XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(doc), new StAXResult(writer));
    }

}

      

+2


source







All Articles