XML Variant 1:
<root>
<elements>
<element />
</elements>
</root>
XML Variant 2:
<root>
<element />
</root>
bean结构是XML Variant 1中每个元素的类,它们如图所示相互嵌套。
理想的行为是unmarshaller为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,但没有成功。什么是实现我想要的最简单方法?
答案 0 :(得分: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);
}
}