Showing posts with label jaxb. Show all posts
Showing posts with label jaxb. Show all posts

Saturday, May 25, 2013

JAXB: Marshalling/Unmarshalling Example

This post shows how you can marshal a JAXB object into XML and unmarshal XML into a JAXB object.

Consider the following JAXB class:

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Book {

  @XmlElement
  private String author;

  @XmlElement
  private String title;
}
Unmarshalling:
To convert an XML string into an object of class Book:
public static Book unmarshal(final String xml) throws JAXBException {
  return (Book) JAXBContext.newInstance(Book.class)
                           .createUnmarshaller()
                           .unmarshal(new StringReader(xml));
}
Marshalling:
To convert a Book object into an XML string:
public static String marshal(Book book) throws JAXBException {
  final Marshaller m = JAXBContext.newInstance(Book.class)
                                  .createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  final StringWriter w = new StringWriter();
  m.marshal(book, w);
  return w.toString();
}

Saturday, March 23, 2013

JAXB MarshalException: Missing an @XmlRootElement Annotation

When marshalling JAXB objects you might get an exception about a missing @XmlRootElement annotation. For example:
javax.xml.bind.MarshalException - with linked exception: 
[com.sun.istack.SAXException2: unable to marshal type "FooType"
as an element because it is missing an @XmlRootElement annotation]
In order to resolve this issue, use the simple binding mode to generate your JAXB classes.

Create the following binding file:

<jaxb:bindings jaxb:extensionBindingPrefixes="xjc" version="2.1"
  xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc">
  <jaxb:globalBindings>
    <xjc:simple/>
  </jaxb:globalBindings>
</jaxb:bindings>
Pass this file to xjc or wsdl2java using the -b option.

You should now see @XmlRootElement annotations on your classes.