没有 XmlRootElement 注释的 JAXB 解组? [英] JAXB unmarshalling without XmlRootElement annotation?

查看:26
本文介绍了没有 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();
          }

}

仅当您在 Customer 类上添加 @XmlAccessorType(XmlAccessType.PROPERTY) 或将所有属性设为私有时,以上代码才有效.

Above code works only if you adding @XmlAccessorType(XmlAccessType.PROPERTY) on Customer class, or make private all attributes.

这篇关于没有 XmlRootElement 注释的 JAXB 解组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆