有几个选项可供您支持此用例。
选项 #1 - XmlAdapter 任何 JAXB (JSR-222) 实现
此方法适用于任何符合 JAXB (JSR-222) 的实现。
值适配器
XmlAdapter 允许您将一个对象编组为另一个对象。在我们的XmlAdapter 中,我们会将String 值转换为/从具有一个与@XmlAttribute 映射的属性的对象。
package forum13489697;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ValueAdapter extends XmlAdapter<ValueAdapter.Value, String>{
public static class Value {
@XmlAttribute
public String value;
}
@Override
public String unmarshal(Value value) throws Exception {
return value.value;
}
@Override
public Value marshal(String string) throws Exception {
Value value = new Value();
value.value = string;
return value;
}
}
人物
@XmlJavaTypeAdapter 注解用于指定XmlAdapter 应与字段或属性一起使用。
package forum13489697;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class Person {
@XmlJavaTypeAdapter(ValueAdapter.class)
public String name;
}
选项 #2 - EclipseLink JAXB (MOXy)
我是 EclipseLink JAXB (MOXy) 负责人,我们提供 @XmlPath 扩展程序,可让您轻松进行基于路径的映射。
人物
package forum13489697;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
public class Person {
@XmlPath("name/@value")
public String name;
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要在与您的域模型相同的包中包含一个名为 jaxb.properties 的文件,其中包含以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示代码
以下演示代码可与任一选项一起使用:
演示
package forum13489697;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13489697/input.xml");
Person person = (Person) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(person, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8"?>
<person>
<name value="arahant" />
</person>