注意: 我是 E clipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
备用映射 - oxm.xml
如果您使用 MOXy 作为您的 JAXB 提供程序,您可以使用外部映射文件为您的域模型提供备用映射(请参阅:http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations。 html ).
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum13843624">
<java-types>
<java-type name="A">
<java-attributes>
<xml-value java-attribute="objectB"/>
</java-attributes>
</java-type>
<java-type name="B">
<java-attributes>
<xml-value java-attribute="hello"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Java 模型
一个
import javax.xml.bind.annotation.*;
@XmlRootElement(name="A")
class A {
private B b;
@XmlElement(name="B")
public B getObjectB() {
return b;
}
public void setObjectB(B b) {
this.b = b;
}
}
乙
import javax.xml.bind.annotation.XmlElement;
class B {
@XmlElement
public String getHello() {
return " world";
}
}
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
演示代码
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
B b = new B();
A a = new A();
a.setObjectB(b);
JAXBContext jc = JAXBContext.newInstance(A.class);
marshal(jc, a);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum13843624/oxm.xml");
JAXBContext jc2 = JAXBContext.newInstance(new Class[] {A.class}, properties);
marshal(jc2, a);
}
private static void marshal(JAXBContext jc, A a) throws Exception {
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(a, System.out);
}
}
输出
下面是运行演示代码的输出。注意同一个对象图是如何以两种不同的方式编组的。
<?xml version="1.0" encoding="UTF-8"?>
<A>
<B>
<hello> world</hello>
</B>
</A>
<?xml version="1.0" encoding="UTF-8"?>
<A> world</A>