Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure JAXB so it trims whitespaces when unmarshalling tag value?

Tags:

java

xml

jaxb

How to configure JAXB unmarshaller so it will trim leading and trailing whitespaces from strings?

For instance let's consider a simple binding between a Java bean and XML using JAXB annotations:

@XmlRootElement(name="bean")
class Bean {

  @XmlElement(required=true)
  String name;

  @XmlElement(required=true)
  int number;
}

I would like to be able to unmarshal XML given bellow so bean.name does not include starting and trailing whitespaces - is "My name", not "\n My name\n ".

<bean>
  <name>
    My name
  </name>
  <number>1</number>
</bean>
like image 744
tkokoszka Avatar asked Dec 11 '08 13:12

tkokoszka


2 Answers

Use a custom Adapter class. I was thinking that NormalizedStringAdapter would do the work but it's only for unmarshaling and it doesn't do what you want anyway.

public class MyNormalizedStringAdapter extends XmlAdapter<String, String> {

    @Override
    public String marshal(String text) {
        return text.trim();
    }

    @Override
    public String unmarshal(String v) throws Exception {
        return v.trim();
    }
}

then decorate the field with your adapter like this:

@XmlElement(required=true)
@XmlJavaTypeAdapter(MyNormalizedStringAdapter.class)
String name;
like image 175
bruno conde Avatar answered Nov 02 '22 04:11

bruno conde


To remove leading and trailing whitespaces during unmarshalling you can use an adapter CollapsedStringAdapter (since Java 1.6).

Built-in XmlAdapter to handle xs:token and its derived types. This adapter removes leading and trailing whitespaces, then truncate any sequnce of tab, CR, LF, and SP by a single whitespace character ' '.

@XmlElement(required=true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
String name;
like image 21
Sergey Nemchinov Avatar answered Nov 02 '22 05:11

Sergey Nemchinov