如何配置JAXB以便在解组标记值时修剪空格? [英] How to configure JAXB so it trims whitespaces when unmarshalling tag value?
问题描述
如何配置JAXB unmarshaller以便它将从字符串中修剪前导空格和尾随空格?
How to configure JAXB unmarshaller so it will trim leading and trailing whitespaces from strings?
例如,让我们考虑使用JAXB注释在Java bean和XML之间进行简单绑定:
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;
}
我希望能够解析下面给出的XML bean .name 不包括起始和尾随空格 - 是我的名字,而不是 \ n我的名字\ n 。
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>
推荐答案
使用自定义适配器类。我在想 NormalizedStringAdapter 会做这项工作,但它只是用于解组而且它不会做你想要的任何事情。
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;
这篇关于如何配置JAXB以便在解组标记值时修剪空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!