没有 XmlRootElement 注释的 JAXB 解组?

JAXB unmarshalling without XmlRootElement annotation?

有没有什么方法可以在没有 @XmlRootElement 注释的情况下为 class 解组?还是我们有义务输入注释?

例如:

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;
    }

}

并让正确注释的 class 的解组代码如下所示:

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

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();
          }

}

只有在客户 class 上添加 @XmlAccessorType(XmlAccessType.PROPERTY) 或将所有属性设为私有时,以上代码才有效。

如果您无法将 XmlRootElement 添加到现有 bean,您还可以创建一个持有者 class 并使用注释将其标记为 XmlRootElement。以下示例:-

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerHolder 
{
    private Customer cusotmer;

    public Customer getCusotmer() {
        return cusotmer;
}

    public void setCusotmer(Customer cusotmer) {
        this.cusotmer = cusotmer;
    }
}