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

后端 未结 2 1097
长发绾君心
长发绾君心 2020-12-17 20:59

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

相关标签:
2条回答
  • 2020-12-17 21:30

    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;
    
    0 讨论(0)
  • 2020-12-17 21:50

    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;
    
    0 讨论(0)
提交回复
热议问题