Java HTML / XML How to - Escape String in JAXB








Question

We would like to know how to escape String in JAXB.

Answer

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
//w  w  w .j  a v a  2s  .  co  m
public class Main {

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

    Response response = new Response();
    response.setMessage("1 < 2");

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

  @XmlRootElement
  public static class Response {

    private String message;

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }

  }
}