我正在使用标准的 JAXB 实现。
这是我的注释类(是一组类的一部分)
@XmlType()
@XmlAccessorType(FIELD)
class MyClass {
@XmlValue
protected final String value = null;
@XmlAttribute
protected String attr;
...get/set for attr...
}
我正在使用 编写根对象
JaxbContext ctx = JAXBContext.newInstance("path.to.package");
XMLStreamWriter writer = new IndentingXMLStreamWriter(file); //stax-utils writer
ctx.marshal(rootObject, writer);
结果是<my-class attr="attrValue"></my-class>
但我需要空标签作为 <my-class attr="attrValue"/>
.
我尝试了编写器和目标流(不仅是文件,还有 StringWriter 等,但我需要将对象保存到文件)的一些不同组合(并阅读了很多 SO 问题)。
有什么建议或解决方案吗?
最佳答案
这是编码到 XMLStreamWriter
时可能会出现的问题。如果您可以编码到 File
、FileOutputStream
或 FileWriter
以获得您正在寻找的行为。
注意:
要使用这些输出目标格式化输出,您可以在 Marshaller
上设置以下属性:
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
关于java - 使用 JAXB 和 XMLStreamWriter 写入空标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27158723/