JAXB unmarshalling without XmlRootElement annotation?

前端 未结 3 724
借酒劲吻你
借酒劲吻你 2021-02-05 12:15

Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?

for example:

public          


        
3条回答
  •  眼角桃花
    2021-02-05 12:56

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

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

提交回复
热议问题