Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure JAXB so it trims whitespaces by default

Tags:

java

trim

xml

jaxb

I would like to configure JAXB so that it trims whitespaces on all string fields

I saw the following answer : How to configure JAXB so it trims whitespaces when unmarshalling tag value?

But I do not want to have to annotate all string fields as per the suggested answer

@XmlElement(required=true)
@XmlJavaTypeAdapter(MyNormalizedStringAdapter.class)
String name;

Thanks!

like image 487
jpboudreault Avatar asked Sep 14 '11 16:09

jpboudreault


1 Answers

  1. Create a XmlAdapter.

    package com.foo.bar;
    public class StringTrimAdapter extends XmlAdapter<String, String> {
        @Override
        public String unmarshal(String v) throws Exception {
            if (v == null)
                return null;
            return v.trim();
        }
        @Override
        public String marshal(String v) throws Exception {
            if (v == null)
                return null;
            return v.trim();
        }
    }
    
  2. Create a package-info.java file in com.foo.bar.

  3. Add the following to the package-info.java file

    @XmlJavaTypeAdapter(value=StringTrimAdapter.class,type=String.class)
    package com.foo.bar;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
    
  4. This will apply StringTrimAdapter to all String fields in com.foo.bar without any extra annotations.

EDIT
Do note that if the package level annotation is too expansive for you, you could always apply a @XmlJavaTypeAdapter annotation to classes.

like image 61
Sahil Muthoo Avatar answered Sep 29 '22 04:09

Sahil Muthoo