Java XML dom: prevent collapsing empty element

心不动则不痛 提交于 2021-01-28 02:56:39

问题


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:


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.



来源:https://stackoverflow.com/questions/19209527/java-xml-dom-prevent-collapsing-empty-element

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