1

XML 变体 1:

<root>
  <elements>
    <element />
  </elements>
</root>

XML 变体 2:

<root>
  <element />
</root>

bean 结构是 XML Variant 1 中每个元素的一个类,它们相互嵌套,如图所示。

解组器所需的行为是为 Variant 2 创建与 Variant 1 相同的 bean。这意味着,它应该创建一个 Elements 类,即使它在结构中不存在。

这是我用于变体 1 的绑定:

<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="demo">
<java-types>
    <java-type name="Root">
        <xml-root-element name="root"/>
        <java-attributes>
            <xml-element java-attribute="elements" xml-path="elements" type="demo.Elements"/>
        </java-attributes>
    </java-type>
    <java-type name="Elements">
        <java-attributes>
            <xml-element java-attribute="element" xml-path="element" type="demo.Element" container-type="java.util.List"/>
        </java-attributes>
    </java-type>
    <java-type name="Element" />
</java-types>

我尝试将 xml-path="elements" 调整为 xml-path="." 并认为这可能适用于变体 2,但没有成功。完成我想要的最简单的方法是什么?

4

1 回答 1

1

您可以为您的用例使用多个映射文件。

映射文件 - 变体 1

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="demo"
    xml-accessor-type="FIELD">
    <java-types>
        <java-type name="Root">
            <xml-root-element/>
        </java-type>
    </java-types>
</xml-bindings>

映射文件 - 变体 2

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="demo"
    xml-accessor-type="FIELD">
    <java-types>
        <java-type name="Root">
            <xml-root-element/>
            <java-attributes>
                <xml-element java-attribute="elements" xml-path="."/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

演示

JAXBContext在下面的演示代码中,我们将为具有不同元数据的同一域模型创建两个不同的实例。

package demo;

import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        // VARIANT #1
        Map<String, Object> properties1 = new HashMap<String, Object>(1);
        properties1.put(JAXBContextProperties.OXM_METADATA_SOURCE, "demo/oxm1.xml");
        JAXBContext jc1 = JAXBContext.newInstance(new Class[] {Root.class}, properties1);
        Unmarshaller unmarshaller1 = jc1.createUnmarshaller();
        File variant1 = new File("src/demo/variant1.xml");
        Root root = (Root) unmarshaller1.unmarshal(variant1);

        // VARIANT #2
        Map<String, Object> properties2 = new HashMap<String, Object>(1);
        properties2.put(JAXBContextProperties.OXM_METADATA_SOURCE, "demo/oxm2.xml");
        JAXBContext jc2 = JAXBContext.newInstance(new Class[] {Root.class}, properties2);
        Marshaller marshaller2 = jc2.createMarshaller();
        marshaller2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller2.marshal(root, System.out);
     }

}
于 2013-07-11T20:09:05.020 回答