如果这个问题已经得到解答,我深表歉意,但我一直在使用的搜索词(即JAXB @XmlAttribute condensed或JAXB XML marshal to String different results)没有提出任何建议。
我正在使用 JAXB 来取消/编组使用@XmlElement
和@XmlAttribute
注释注释的对象。我有一个格式化程序类,它提供了两种方法——一种包装了 marshal 方法并接受要编组和 an 的对象OutputStream
,另一种只接受对象并将 XML 输出作为字符串返回。不幸的是,这些方法不会为相同的对象提供相同的输出。编组到文件时,内部标记为的简单对象字段@XmlAttribute
打印为:
<element value="VALUE"></element>
而当编组为字符串时,它们是:
<element value="VALUE"/>
对于这两种情况,我更喜欢第二种格式,但我很好奇如何控制差异,并且无论如何都会满足于它们的相同。我什至创建了一个静态编组器,两种方法都使用它来消除不同的实例值。格式化代码如下:
/** Marker interface for classes which are listed in jaxb.index */
public interface Marshalable {}
/** Local exception class */
public class XMLMarshalException extends BaseException {}
/** Class which un/marshals objects to XML */
public class XmlFormatter {
private static Marshaller marshaller = null;
private static Unmarshaller unmarshaller = null;
static {
try {
JAXBContext context = JAXBContext.newInstance("path.to.package");
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
unmarshaller = context.createUnmarshaller();
} catch (JAXBException e) {
throw new RuntimeException("There was a problem creating a JAXBContext object for formatting the object to XML.");
}
}
public void marshal(Marshalable obj, OutputStream os) throws XMLMarshalException {
try {
marshaller.marshal(obj, os);
} catch (JAXBException jaxbe) {
throw new XMLMarshalException(jaxbe);
}
}
public String marshalToString(Marshalable obj) throws XMLMarshalException {
try {
StringWriter sw = new StringWriter();
return marshaller.marshal(obj, sw);
} catch (JAXBException jaxbe) {
throw new XMLMarshalException(jaxbe);
}
}
}
/** Example data */
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Data {
@XmlAttribute(name = value)
private String internalString;
}
/** Example POJO */
@XmlType
@XmlRootElement(namespace = "project/schema")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container implements Marshalable {
@XmlElement(required = false, nillable = true)
private int number;
@XmlElement(required = false, nillable = true)
private String word;
@XmlElement(required = false, nillable = true)
private Data data;
}
调用结果marshal(container, new FileOutputStream("output.xml"))
如下marshalToString(container)
:
输出到文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:container xmlns:ns2="project/schema">
<number>1</number>
<word>stackoverflow</word>
<data value="This is internal"></data>
</ns2:container>
和
输出到字符串
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:container xmlns:ns2="project/schema">
<number>1</number>
<word>stackoverflow</word>
<data value="This is internal"/>
</ns2:container>