简体   繁体   English

Java中XML空元素的输出格式

[英]Output format of XML empty element in Java

I wrote code below to get XML output. 我在下面编写了代码以获取XML输出。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();

Element element = document.createElement("Test");
Text text = document.createTextNode("");
element.appendChild(text);
document.appendChild(element);

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

What I got is 我得到的是

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test/>

What I want to get is 我想要得到的是

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test></Test>

How can I do this? 我怎样才能做到这一点?

Many thanks. 非常感谢。

There is no clean way to do this.. 没有干净的方法可以做到这一点。

If you feel comfortable to use duct-tape solutions, you could let your transformer output html instead of xml: 如果您愿意使用风管胶带解决方案,则可以让变压器输出html而不是xml:

transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "html");

But again, I have to point out that this is not a clean solution, but it did the trick for me as I was stuck with a similar problem 但是,我必须指出,这不是一个干净的解决方案,但是它对我有用,因为我遇到了类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM