English 中文(简体)
java XML 序列器避免复杂的空元素
原标题:java XMLSerializer avoid Complex Empty Elements

我有这个密码:

    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>

Does anybody know, how to set the XMLSerializer to avoid Complex Empty Elements? Thanks.

最佳回答

我对 XMLSregister 不允许对空标签进行定制也有同样的问题。 我的解决方案是扩展 XMLSregize 原代码, 并推翻序列 E元素方法 :

我复制了原代码 并更改了关闭打印部分:

protected void serializeElement(Element elem) throws IOException ...

if (isSelfClosingElement(elem))
    _printer.printText("/>");
else
_printer.printText("></" + elem.getTagName() + ">");

" 强者 " 拥有自闭元素清单的 " 强者 " 持有自闭元素清单的 " 强者 "

NOTE: 额外, 您需要复制 < strong > printAttritte () 和 < strong > printNamespaceAttr () 方法, 因为它是私人标记, 而不是受保护的 。

问题回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签