4

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

see transformer.setOutputProperty(OutputKeys.METHOD, "html");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.