注: 私はE clipeLink JAXB(MOXy)のリーダーであり、JAXB(JSR-222)エキスパートグループのメンバーです。
代替マッピング-oxm.xml
JAXBプロバイダーとしてMOXyを使用している場合は、外部マッピングファイルを使用して、ドメインモデルの代替マッピングを提供できます(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モデル
A
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;
}
}
B
import javax.xml.bind.annotation.XmlElement;
class B {
@XmlElement
public String getHello() {
return " world";
}
}
jaxb.properties
JAXBプロバイダーとしてMOXyを指定するには、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);
}
}
出力
以下は、デモコードの実行からの出力です。同じオブジェクトグラフが2つの異なる方法でマーシャリングされる方法に注意してください。
<?xml version="1.0" encoding="UTF-8"?>
<A>
<B>
<hello> world</hello>
</B>
</A>
<?xml version="1.0" encoding="UTF-8"?>
<A> world</A>