开发者

How to get String representation of XmlType?

Is it possible to convert a javax.xml.bind.annotation.XmlType to the String representation of the XML?

Example:

The following class Req is from a third party library so I can't override the toString() method.

@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
@javax.xml.bind.annotation.XmlType(name = "req", propOrder = {"myDetails", "customerDetails"})
public class Req  {
...
}

In my application I wan开发者_运维技巧t to simply get a String representation of the XML so that I can log it to a file:

<Req>
    <MyDetails>
    ...
    </MyDetails>
    <CustomerDetails>
    ...
    </CustomerDetails>
</Req>

When I try to use JAXB and Marshall to convert to XML String:

JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);
String xmlString = sw.toString();

I get the following exception:

javax.xml.bind.MarshalException
    - with linked exception:
    [com.sun.istack.SAXException2: unable to marshal type "mypackage.Req" as an element because it is missing an @XmlRootElement annotation]

I have had a look at the other classes within the third party library and none of them use the @XmlRootElement annotation. Any way around this?


You can use JAXB and marshall it to xml string

JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);

String xmlString = sw.toString();


Addding to what Bala R indicated, you can do this if your JAXB element don't have the @xmlrootelement

JAXBContext context = JAXBContext.newInstance(YourClass.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            StringWriter sw = new StringWriter();
            JAXBElement jx = new JAXBElement(new QName("YourRootElement"), YourClass.class, input);
            marshaller.marshal(jx, sw);
            String xmlString = sw.toString();

This was also stated here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜