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
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 to share