Java HTML / XML How to - Create JAXBElement from String








Question

We would like to know how to create JAXBElement from String.

Answer

import java.io.StringReader;
//from ww w. j a va 2s  .c  om
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class Main {
  String title;
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }
  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Main.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    String code = "<book><title>Harry Potter</title></book>";
    StreamSource source = new StreamSource(new StringReader(code));
    JAXBElement<Main> jaxbElement = unmarshaller.unmarshal(source, Main.class);
  }
}