我有这个代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
Document xmldoc = impl.createDocument(null, null, null);
Element root = xmldoc.createElement("root");
Element textElement = xmldoc.createElement("text");
Text textNode = xmldoc.createTextNode("");
root.appendChild(textElement);
textElement.appendChild(textNode);
OutputFormat of = new OutputFormat("XML","UTF-8",true);
of.setIndent(1);
of.setIndenting(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
XMLSerializer serializer = new XMLSerializer(stream, of);
// As a DOM Serializer
serializer.asDOMSerializer();
serializer.serialize(root);
System.out.println(stream.toString());
我要安慰一下:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<text/>
</root>
但是,我想得到这个:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<text></text>
</root>
有谁知道,如何设置 XMLSerializer 以避免复杂的空元素?谢谢。