如何配置 JAXB 以便在解组标记值时修剪空格? [英] How to configure JAXB so it trims whitespaces when unmarshalling tag value?
问题描述
如何配置 JAXB 解组器,以便它修剪字符串中的前导和尾随空格?
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>
推荐答案
使用自定义 Adapter 类.我在想 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屋!