在Java中,JAXB(Java Architecture for XML Binding)是一种将Java对象与XML文档之间进行转换的技术。要在解组标记值时修剪空格,您需要使用自定义的XML适配器。以下是如何实现此目的的步骤:
javax.xml.bind.annotation.adapters.XmlAdapter
接口。import javax.xml.bind.annotation.adapters.XmlAdapter;
public class TrimmingAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) {
return v.trim();
}
@Override
public String marshal(String v) {
return v;
}
}
@XmlJavaTypeAdapter
注解,并指定您在第1步中创建的适配器类。import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class MyObject {
@XmlElement
@XmlJavaTypeAdapter(TrimmingAdapter.class)
private String trimmedField;
@XmlAttribute
@XmlJavaTypeAdapter(TrimmingAdapter.class)
private String trimmedAttribute;
}
MyObject
类的trimmedField
和trimmedAttribute
字段将自动修剪空格。import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class Main {
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(MyObject.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
MyObject myObject = (MyObject) unmarshaller.unmarshal(new File("path/to/xml/file.xml"));
System.out.println(myObject.getTrimmedField());
System.out.println(myObject.getTrimmedAttribute());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
通过使用自定义的XML适配器,您可以确保在JAXB解组标记值时修剪空格。这种方法适用于所有需要修剪空格的字段,无需更改JAXB生成的代码。
领取专属 10元无门槛券
手把手带您无忧上云