preventing empty xml elements are converted to sel

2019-07-06 05:13发布

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,

标签: java xml xerces
2条回答
看我几分像从前
2楼-- · 2019-07-06 06:00

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));
    }

}
查看更多
爷、活的狠高调
3楼-- · 2019-07-06 06:02

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.

查看更多
登录 后发表回答