Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get String representation of XmlType?

Tags:

java

xml

jaxb

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 want 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?

like image 886
ryan Avatar asked May 17 '11 14:05

ryan


1 Answers

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();
like image 177
Bala R Avatar answered Oct 04 '22 10:10

Bala R