Java XML dom:防止折叠空元素 [英] Java XML dom: prevent collapsing empty element
问题描述
我使用 javax.xml.parsers.DocumentBuilder
,并想将 org.w3c.dom.Document
写入文件.
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>
感谢您的帮助.
推荐答案
这实际上取决于您将文档写入文件的方式,并且与DOM本身无关.以下示例使用了流行的基于Transformer的方法:
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);
它按预期输出< tag></tag>
.请注意,更改输出方法还有其他副作用,例如缺少XML声明.
It outputs <tag></tag>
as you're expecting. Please note, that changing the output method has other side effects, like missing XML declaration.
这篇关于Java XML dom:防止折叠空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!