JAXB unmarshalling without XmlRootElement annotation?

前端 未结 3 586
借酒劲吻你
借酒劲吻你 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:58

    I use the generic solution as follows:

    public static  String objectToXmlStringNoRoot(T obj, Class objClass, final String localPart) throws JAXBException {
    
        JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    
        // To format XML
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    
        //If we DO NOT have JAXB annotated class
        JAXBElement jaxbElement = new JAXBElement<>(new QName("", localPart), objClass, obj);
    
        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(jaxbElement, sw);
    
        return sw.toString();
    }
    

提交回复
热议问题