Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XML dom: prevent collapsing empty element

Tags:

java

dom

xml

I use the javax.xml.parsers.DocumentBuilder, and want to write a org.w3c.dom.Document to a file.

If there is an empty element, the default output is a collapsed:

<element/>

Can I change this behavior so that is doesn't collapse the element? I.e.:

<element></element>

Thanks for your help.

like image 562
Terry Avatar asked Oct 25 '25 14:10

Terry


1 Answers

This actualy depends on the way how you're writing a document to a file and has nothing to do with DOM itself. The following example uses popular Transformer-based approach:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      
Document document = factory.newDocumentBuilder().newDocument();             
Element element = document.createElement("tag");                            
document.appendChild(element);                                              
TransformerFactory transformerFactory = TransformerFactory.newInstance();   
Transformer transformer = transformerFactory.newTransformer();              
transformer.setOutputProperty(OutputKeys.METHOD, "html");                   
DOMSource source = new DOMSource(document);                                 
StreamResult result = new StreamResult(System.out);                         
transformer.transform(source, result);                                 

It outputs <tag></tag> as you're expecting. Please note, that changing the output method has other side effects, like missing XML declaration.

like image 70
Jk1 Avatar answered Oct 28 '25 05:10

Jk1