除了虚构一个编写器并将每个元素附加到字符串上之外,是否有一种方法可以让JAXB marshaller对对象列表进行编组,我只需给出顶部元素的名称?
我觉得我离成功很近了。
//http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html
public <T> String jaxb(Collection<T> o, Class<T> clazz, String plural){
try {
ArrayList<T> al = new ArrayList<T>(o.size());
al.addAll(o);
JAXBContext jc = JAXBContext.newInstance(ArrayList.class);
JAXBElement<ArrayList> amenity = new JAXBElement(new QName(plural), ArrayList.class, al);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(amenity, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
但是结果仍然返回一个空列表。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pluralName/>
有没有一种方法可以不仅仅是手动粘贴xml字符串就能完成这个操作?
更新
在Michael Glavassevich的帮助下,我已经能够完成这个操作,只有一个限制,即单独的元素是<Item>
。
//http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> String jaxb(Collection<T> elements, Class<T> elementClass, String plural){
try {
T[] array = (T[]) Array.newInstance(elementClass, elements.size());
elements.toArray(array);
JAXBContext jc = JAXBContext.newInstance(array.getClass());
JAXBElement<T[]> topElement = new JAXBElement(new QName(plural), array.getClass(), array);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(topElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
结果就变成了:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Basketballs>
<item>basketball one</item>
<item>basketball two</item>
</Basketballs>
JAXBContext.newInstance()
吗?显然我不能使用JAXBContext.newInstance(T[].class)
。 - mike<item>
。你有任何想法如何更改它吗? - mike<xs:element name="item" type=schematype minOccurs="0" maxOccurs="unbounded" nillable="true"/>
的模式类型。至少在规范级别上,这是不可配置的。 - Michael Glavassevich