Java HTML / XML How to - Use JAXB to unmarshall xml without xml declaration








Question

We would like to know how to use JAXB to unmarshall xml without xml declaration.

Answer

import java.io.StringReader;
/*w  ww. j  a va2 s  .co m*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Main {
  private String bar;

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Main.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    StringReader xml = new StringReader("<main><bar>Hello World</bar></main>");
    Main foo = (Main) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(foo, System.out);
  }

}