没有实际组成一个编写器并将每个元素附加到字符串上。有没有一种方法可以让JAXB编组器编组对象列表,而我可以在上面给出顶层元素的名称?
我觉得我已经很接近了
//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字符串粘贴在一起?
从迈克尔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>
如果您不想创建包装器类,则可以将集合转换为数组,将该数组放入a中JAXBElement
,然后将其封送。
例如:
public class JAXBArrayWriter {
public static class Item {
@XmlValue
protected String value;
public Item() {}
public Item(String value) {
this.value = value;
}
}
public static void main (String [] args) throws Exception {
List<Item> items = new ArrayList<Item>();
items.add(new Item("one"));
items.add(new Item("two"));
JAXBContext jc = JAXBContext.newInstance(Item[].class);
JAXBElement<Item[]> root = new JAXBElement<Item[]>(new QName("items"),
Item[].class, items.toArray(new Item[items.size()]));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(root, writer);
System.out.println(writer.toString());
}
}
产生以下文档:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items>
<item>one</item>
<item>two</item>
</items>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句