Arnob Ghosh
Arnob Ghosh

Reputation: 31

preventing empty xml elements are converted to self closing elements

I am using Xerces Library for writing XML in document . For that I am using OutputFormat class passing the object of OutputFormat in XMLSerializer. But all of my empty xml elements are converted to self-closing xml elements.

I want this:

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

But its coming like

<Company Name="Dummy" />

I have tried below code:

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 out on this.

Thanks,

Upvotes: 3

Views: 3059

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

Most serializers I know of do not 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 whether they are used or not. If you do care, and are not insane, it would help to explain why you care.

Upvotes: 3

shlomi33
shlomi33

Reputation: 1568

If you are willing to use other APIs to resolve the issue 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));
    }

}

Upvotes: 3

Related Questions