问题描述
我正在尝试将列表编组为xml。由于xml包含列表,并且我不想为外部标记创建单独的类,因此我将STAX和JAXB结合使用。
<WRAPPER>
<ROOT att1="val1" att2="val2"></ROOT>
<ROOT att1="val1" att2="val2"></ROOT>
</WRAPPER>
预期产量
<WRAPPER>
<ROOT att1="val1" att2="val2"/>
<ROOT att1="val1" att2="val2"/>
</WRAPPER>
类文件
@XmlRootElement(name="ROOT")
@XmlAccessorType(XmlAccesstype.FIELD)
public class ROOT {
@XmlAttribute(name = "att1")
String att1;
@XmlAttribute(name = "att2")
String att2;
public String getAtt1() {
return att1;
}
public void setAtt1(String att1) {
this.att1 = att1;
}
public String getAtt2() {
return att2;
}
public void setAtt2(String att2) {
this.att2 = att2;
}
}
public static String marshal(List<ROOT> list)
throws XMLStreamException,JAXBException,IOException {
JAXBElement<ROOT> jaxb = null;
String xmlString = null;
if (!CollectionUtils.isEmpty(list)) {
QName root = new QName("ROOT");
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
StringWriter stringWriter = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(stringWriter);
streamWriter.writeStartElement("WRAPPER");
JAXBContext jc = JAXBContext.newInstance(ROOT.class);
Marshaller marshaller = jc.createMarshaller();
for (ROOT t : list) {
jaxb = new JAXBElement<ROOT>(root,ROOT.class,t);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
marshaller.marshal(jaxb,streamWriter);
}
streamWriter.writeEndDocument();
xmlString = stringWriter.toString();
stringWriter.close();
streamWriter.close();
}
return xmlString;
}
问题是不可适用的,不能应用于XmlRootElement
解决方法
尽管期望值和实际值在技术上都是相等的,但我发现无法在不创建其他包装器类的情况下进行修改。