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
 
 bar
if marshal data xml, literal line feed characters in output. apparently against xml standards characters should encoded 
. ie in xml file output should see:
foo 
bar
but if try , manually, end ampersand getting encoded!
foo &#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
world</foo></root>
update
below additional details based on investigation did.
common jaxb (jsr-222) implementations
- if marshalling
xmlstreamwriter
orxmleventwriter
directly (viamarshaller
) 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)
- there bug in moxy related escaping
\r
in process of fixing (see: http://bugs.eclipse.org/414608)
jaxb reference implementation
- the jaxb reference implementation escape '\r' when marshalling
outputstream
, notwriter
atleast in jdk i'm using.
Comments
Post a Comment