Java 以编程方式添加或设置JAXB XmlRootElement
我希望避免将注释@XMLRootElement添加到每个POJO中,我将使用它来解组xml。有没有办法通过编程方式将XmlRootElement设置或添加到类中Java 以编程方式添加或设置JAXB XmlRootElement,java,xml,jaxb,Java,Xml,Jaxb,我希望避免将注释@XMLRootElement添加到每个POJO中,我将使用它来解组xml。有没有办法通过编程方式将XmlRootElement设置或添加到类中 //@XmlRootElement here public class Person{ private String name; private String address; //other fields //getters and setters here 如果不可能,如何在POJO中不使
//@XmlRootElement here
public class Person{
private String name;
private String address;
//other fields
//getters and setters here
如果不可能,如何在POJO中不使用XmlRootElement的情况下解组xml
public static <T> T unmarshal(Class clazz, String xml) {
try {
JAXBContext ctx = JAXBContext.newInstance(clazz);
Unmarshaller u = ctx.createUnmarshaller();
return (T) u.unmarshal(new StringReader(xml));
} catch (JAXBException e) {
throw new RuntimeException("Error interpreting XML response", e);
}
}
编辑:
布莱斯的回答确实有效
StreamSource source = new StreamSource(new StringReqder(xml));
return (T) u.unmarshal(source, clazz).getValue();
但是当我试图用它返回一个列表时
//this works when I specify @XmlRootElement
private static <T> List<T> unmarshallCollection(Class<T> clazz, Source source)
throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(WrapperCollection.class, clazz);
Unmarshaller u = ctx.createUnmarshaller();
WrapperCollection<T> collection = u.unmarshal(source, WrapperCollection.class).getValue();
return collection.getItems();
}
//当我指定@XmlRootElement时,这就起作用了
私有静态列表解组集合(类clazz,源)
抛出异常{
JAXBContext ctx=JAXBContext.newInstance(WrapperCollection.class,clazz);
解组器u=ctx.createUnmarshaller();
WrapperCollection collection=u.unmarshal(源,WrapperCollection.class).getValue();
return collection.getItems();
}
并且它抛出一个异常,org.apache.xerces.dom.ElementNSImpl不能被强制转换为。。
我做错了什么?您只需要使用一个采用
类
参数的解组
方法
StreamSource source = new StreamSource(new StringReqder(xml));
return (T) u.unmarshal(source, clazz).getValue();
注意
- unmarshal方法的结果将是
的一个实例,它保存根元素信息,您可以通过调用JAXBElement
来获取unmarshalled对象getValue
- 对于封送,可以通过将对象包装在
的实例中,然后封送来提供根信息JAXBElement
StreamSource source = new StreamSource(new StringReqder(xml));
return (T) u.unmarshal(source, clazz).getValue();