没有XmlRootElement注释的JAXB解组? [英] JAXB unmarshalling without XmlRootElement annotation?
本文介绍了没有XmlRootElement注释的JAXB解组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于没有@XmlRootElement注释的类,我们有什么方法可以解组?或者我们是否有义务输入注释?
Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?
例如:
public class Customer {
private String name;
private int age;
private int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
并让正确的解组码注释类如:
and let the unmarshalling code for properly annotated class be like:
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}
省略细节。
推荐答案
以下代码用于编组和取消联合 @XmlRootElement
Following code is used to marshall and unmarshall withot @XmlRootElement
public static void main(String[] args) {
try {
StringWriter stringWriter = new StringWriter();
Customer c = new Customer();
c.setAge(1);
c.setName("name");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(new JAXBElement<Customer>( new QName("", "Customer"), Customer.class, null, c), stringWriter);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
JAXBElement<Customer> customer = (JAXBElement<Customer>) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class);
c = customer.getValue();
} catch (JAXBException e) {
e.printStackTrace();
}
}
以上代码仅在您添加时有效客户类上的 @XmlAccessorType(XmlAccessType.PROPERTY)
,或者将所有属性设为私有。
Above code works only if you adding @XmlAccessorType(XmlAccessType.PROPERTY)
on Customer class, or make private all attributes.
这篇关于没有XmlRootElement注释的JAXB解组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文