注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB 2 (JSR-222)专家组的成员。
对于这个用例,我建议使用字段访问类型。指定此项后,JAXB 实现将使用字段(实例变量)来访问数据,而不是通过属性(get 方法)。下面我将演示如何使用 MOXy 的外部映射文档扩展来做到这一点:
绑定.xml
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum10141543">
<java-types>
<java-type name="Name" xml-accessor-type="FIELD">
<xml-root-element/>
</java-type>
</java-types>
</xml-bindings>
姓名
package forum10141543;
class Name {
private String first;
private String middle;
private String last;
public Name() {
}
public Name(String first, String middle, String last) {
this.first = first;
this.middle = middle;
this.last = last;
}
public String getFirst() { return first; }
public String getMiddle() { return middle; }
public String getLast() { return last; }
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要添加一个jaxb.properties
在与您的域类相同的包中调用的文件,其中包含以下条目。
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
演示
以下代码演示了如何在引导时传入绑定文件JAXBContext
:
package forum10141543;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum10141543/bindings.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Name.class}, properties);
Name name = new Name("Jane", "Anne", "Doe");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(name, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8"?>
<name>
<first>Jane</first>
<middle>Anne</middle>
<last>Doe</last>
</name>
了解更多信息