Java HTML / XML How to - Deal with linebreaks in strings








Question

We would like to know how to deal with linebreaks in strings.

Answer

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
/*  w  w  w  . java2  s  .co m*/
public class Main {

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

    Root root = new Root();
    root.setFoo("Hello\rWorld");
    root.setBar("Hello\nWorld");

    Marshaller marshaller = jc.createMarshaller();
    marshaller.marshal(root, System.out);
  }

  @XmlRootElement
  public static class Root {

    private String foo;
    private String bar;

    public String getFoo() {
      return foo;
    }

    public void setFoo(String foo) {
      this.foo = foo;
    }

    public String getBar() {
      return bar;
    }

    public void setBar(String bar) {
      this.bar = bar;
    }

  }
}