Question

IS there a way to marshall/unmarshall xml/object multiline attributes .

Currently it is showing as

<task name="Payament Gateway
Checker" >

It would be best , if store it by replacing nextline whitespace with \n ?

<task name="Payament Gateway \n Checker" >

Edit -

Tried Both Adapter and JaxbListener - but converted to name="Payament Gateway &#xA; Checker"

void beforeMarshal(Marshaller marshaller) {
 name = name.replaceAll("\n", "&#xA;");    
 }

@XmlJavaTypeAdapter(MultilineString.class)
    @XmlAttribute
    protected String name;

public class MultilineString extends XmlAdapter<String, String> {
    @Override
    public String marshal(String input) throws Exception {
        return input.replaceAll("\n", "&#xA;");
    }
    @Override
    public String unmarshal(String output) throws Exception {
        return output;
    }
}
Was it helpful?

Solution

TL;DR

JAXB should be replacing the Java \n with &#xA; which is the proper XML escaping. If you are not seeing this then there may be a bug in the version of the JAXB implementation you are using. For example this issue was fixed in EclipseLink JAXB (MOXy) in version 2.5.1:


Example

Java Model (Foo)

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Foo {

    private String bar;

    @XmlAttribute
    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(Foo.class);

        Foo foo = new Foo();
        foo.setBar("Hello\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 bar="Hello&#xA;World"/>

Workaround

You can always use an XmlAdapter to control any output in JAXB.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top