JAXB seems to be re-encoding new line char

2019-04-15 01:22发布

I have the following code...

public static final String NEWLINE = String.format("%n");
...
StringBuilder b = new StringBuilder();
...
b.append(NEWLINE);
return b.toString();

However when I run this in SOAPUI and look at the RAW it looks like it is augmenting it again and the new line turns into



So instead of

<SOAPEnvelope>1,name,value
             2,name,value<SOAPEnvelope>

It shows up as...

<SOAPEnvelope>1,name,value&#xD;
             2,name,value&#xD;<SOAPEnvelope>

So when I parse using a regex query to replace with an empty string the full text is still around

Now I am not as familiar with encoding but this is the payload of a SOAP message. The envelope is stripped away and this is ouputed to a CSV file. When I open the CSV in Notepad++ the new line char appears to work but that encoded value is still there. Does anyone know what I am missing?

I tried adding a (sb = Stringbuilder)

sb.append("<![CDATA[");
...
sb.append("]]>");

But this doesn't seem to work, again JAXB seems to escape the chars.

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><ns4:ReportResult xmlns:ns2="http://me.com/v1_9/service" xmlns:ns3="http://me.com/v1_9/service/objects" xmlns:ns4="http://me.com/v1_9/service/operations">&lt;![CDATA[000000,LK20130930120048,Compant,Data,20130930120048,,&#xD;
000001,user,Fname,Mname,Lname,12345 Address 1,Address 2222,setAddress3,setCity,OH,US,44332,,N,N,E,,,,?,,&#xD;
999999]]&gt;</ns4:ReportResult></soapenv:Body></soapenv:Envelope>

Also I would be fine with something like this but I use the default marshaller for JAX-WS. So I am not exactly sure where to put it.

2条回答
趁早两清
2楼-- · 2019-04-15 01:53

Try to wrap the special character in a <![CDATA[ ]]> block. It should avoid the re-encoding.

查看更多
相关推荐>>
3楼-- · 2019-04-15 02:05

A JAXB (JSR-222) implementation will do the following:

  • \n will be written to XML as a new line.
  • \r will be escaped as &#xD;

Demo Code

Foo

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

    public String slashN;
    public String slashR;
    public String slashRslashN;

}

Demo

import javax.xml.bind.*;

public class Demo {

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

        Foo foo = new Foo();
        foo.slashN = "Hello\nWorld";
        foo.slashR = "Hello\rWorld";
        foo.slashRslashN = "Hello\r\nWorld";

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

}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <slashN>Hello
World</slashN>
    <slashR>Hello&#xD;World</slashR>
    <slashRslashN>Hello&#xD;
World</slashRslashN>
</foo>
查看更多
登录 后发表回答