preventing empty xml elements are converted to self closing elements

白昼怎懂夜的黑 提交于 2019-12-10 20:38:18

问题


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,


回答1:


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.




回答2:


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

}


来源:https://stackoverflow.com/questions/25588555/preventing-empty-xml-elements-are-converted-to-self-closing-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!