没有XmlRootElement注释的JAXB解组?

有没有什么方法可以为没有@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(); } 

遗漏了细节。

以下代码用于编组和取消编组@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( new QName("", "Customer"), Customer.class, null, c), stringWriter); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes()); JAXBElement customer = (JAXBElement) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class); c = customer.getValue(); } catch (JAXBException e) { e.printStackTrace(); } } 

上面的代码只有在Customer类上添加@XmlAccessorType(XmlAccessType.PROPERTY)或者将所有属性@XmlAccessorType(XmlAccessType.PROPERTY)

如果无法将XmlRootElement添加到现有bean,则还可以创建holder类并使用注释将其标记为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; } }