我正在使用标准的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);