How should I deal with linebreaks in strings I want to marshal in Java to XML? -


how should deal linebreaks in strings want marshal xml?

i having difficulty using java , jaxb handle putting strings in xml files have linefeeds in them. data being pulled database actual line feed characters in them.

foo <lf> bar 

or additional example:

foo\r\n\r\nbar 

yields:

foo&#xd; &#xd; bar 

if marshal data xml, literal line feed characters in output. apparently against xml standards characters should encoded &#xd;. ie in xml file output should see:

foo &#xd;bar

but if try , manually, end ampersand getting encoded!

foo &amp;#xd;bar

this pretty ironic because process apparently supposed encode linebreaks in first place , not, foiling attempts encode manually.

below example of jaxb's default behaviour regarding \n , \r:

java model (root)

import javax.xml.bind.annotation.xmlrootelement;  @xmlrootelement public 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;     }  } 

demo code

import javax.xml.bind.*;  public class demo {      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);     }  } 

output

<?xml version="1.0" encoding="utf-8" standalone="yes"?><root><bar>hello world</bar><foo>hello&#xd;world</foo></root> 

update

below additional details based on investigation did.

common jaxb (jsr-222) implementations

  • if marshalling xmlstreamwriter or xmleventwriter directly (via marshaller) or indirectly (via potentially jax-rs or jax-ws provider) escaping based on stax implementation. woodstox appears escape things correctly, stax implementation in jdk i'm using did not.

eclipselink jaxb (moxy)

jaxb reference implementation

  • the jaxb reference implementation escape '\r' when marshalling outputstream, not writer atleast in jdk i'm using.

Comments

Popular posts from this blog

Need help in packaging app using TideSDK on Windows -

java - Why does my date parsing return a weird date? -