使用MOXy实现“xml-elements”

时间:2011-03-15 13:54:36

标签: jaxb eclipselink moxy


我想知道如何使用EclipseLink MOXy实现具有接口类型的List,
之前,使用JAXB,以下注释完成了作业

class A {

   @XmlElements({
       @XmlElement(name = "B1", type = B1.class),
       @XmlElement(name = "B2", type = B2.class)
    })
    List< B > list;

}

interface B{}

class B1 implements B {}

class B2 implements B {} 

支持接口类型列表???

1 个答案:

答案 0 :(得分:2)

我领导EclipseLink JAXB (MOXy)。我无法重现您的问题。你能提供你看到的堆栈跟踪吗?以下是我的尝试:

<强>演示

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.eclipse.persistence.Version;

public class Demo {

    public static void main(String[] args) throws Exception {
        System.out.println(Version.getVersionString());

        JAXBContext jc = JAXBContext.newInstance(A.class, B1.class, B2.class);
        System.out.println(jc);

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        JAXBElement<A> root = unmarshaller.unmarshal(new StreamSource(xml), A.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

<强> jaxb.properties

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

<强> input.xml中

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <B1/>
   <B2/>
</root>

<强>输出

2.2.0.v20110202-r8913
org.eclipse.persistence.jaxb.JAXBContext@11ddcde
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <B1/>
   <B2/>
</root>

使用EclipseLink JAXB(MOXy)的XML元数据文件

MOXy还有一个扩展,可以将元数据作为XML文件提供。下面是这个例子的样子:

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="com.example">
    <java-types>
        <java-type name="A">
            <java-attributes>
                <xml-elements java-attribute="list">
                    <xml-element name="B1" type="com.example.B1"/>
                    <xml-element name="B2" type="com.example.B2"/>
                </xml-elements>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

创建JAXBContext时,此元数据文件作为属性传入:

Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new File("src/forum149/bindings.xml"));
JAXBContext jc = JAXBContext.newInstance(new Class[] {A.class, B1.class, B2.class}, properties);

有关详细信息,请参阅: