我正在尝试使用Java中的 Marshaller 类将 POJO 序列化为 XML 。有没有办法在 marshal()操作中删除一些已知字符(*,+, - )?
答案 0 :(得分:0)
如果要删除的字符是String实例,则使用JAXB适配器的方法很简单。 如果它适用于其他类,则此处提供的一般逻辑保持不变。
适配器类:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class StringAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String string) throws Exception {
return string;
}
@Override
public String marshal(String string) throws Exception {
return string.replaceAll("[*+-]", "");
}
}
然后配置您的XmlAdapter,以便在编组期间使用它 你可以在jaxb绑定文件(http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html)中进行操作,如果你想使用Jaxb为所有pojo类进行泛化,或者你可以通过String字段上的Annotation直接在目标pojo类中应用适配器:
@XmlJavaTypeAdapter(value = StringAdapter.class)
private String string;