Wednesday, July 31, 2013

JAXB - Unmarshal an XML String

jaxb logo
When trying to unmarshal an XML to a Java object using JAXB you might want to pass the XML as a String. However the unmarshal() method of the Unmarshaller interface does not support passing an XML String. Following code sample illustrates how to solve this.


Wrap the XML String in a StringReader object and pass this to the unmarshal() method as shown below:

public static Car unmarshal(String xml) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader(xml);
Car car = (Car) jaxbUnmarshaller.unmarshal(reader);

LOGGER.info(car.toString());
return car;
}

Pass below string representation of an XML to the above unmarshal() method.

xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" "
+ "standalone=\"yes\"?>"
+ "<ns2:Car xmlns:ns2=\"info.source4code.jaxb.model\" id=\"ABC-123\">"
+ "<make>Passat</make>"
+ "<manufacturer>Volkswagen</manufacturer></ns2:Car>";

JAXB is now able to unmarshal the StringReader object and the result is the following:

Car [make=Passat, manufacturer=Volkswagen, id=ABC-123]


github icon
If you would like to run the above code sample you can download the full source code and their corresponding JUnit test cases here.

This concludes the unmarshal an XML String code example. If you found this post helpful or have any questions or remarks, please leave a comment.

No comments:

Post a Comment