JAXB 取消编组而没有 XmlRootElement annotation?

2022-09-02 19:59:24

有没有办法在不@XmlRootElement注释的情况下为类取消元组?还是我们有义务输入注释?

例如:

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

}

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

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

省略细节。


答案 1

以下代码用于 marshall 和 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)


答案 2

如果无法将 XmlRootElement 添加到现有 Bean 中,还可以创建一个持有者类,并用注释将其标记为 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;
    }
}

推荐