我有以下java模型:
public class Container {
public X x;
public Y y;
}
public class X {
public String test;
}
public class Y {}
并希望映射以下文档:
<?xml version="1.0" encoding="UTF-8"?>
<my:root xmlns:my="http://my.url" test="value">
<x/>
</my:root>
为此,我使用了绑定文件:
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="example">
<xml-schema namespace="http://my.url" />
<java-types>
<java-type name="Container">
<xml-root-element name="root"/>
<xml-type namespace="http://my.url" />
<java-attributes>
<xml-element java-attribute="x" xml-path="x" type="example.X"/>
<xml-element java-attribute="y" xml-path="." type="example.Y"/>
</java-attributes>
</java-type>
<java-type name="Y">
<java-attributes>
<xml-element java-attribute="test" xml-path="@test"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
失败并出现异常:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element {http://my.url}root was not found in the project]
at org.eclipse.persistence.jaxb.JAXBBinder.unmarshal(JAXBBinder.java:100)
at example.Main.main(Main.java:39)
给定文档的模型不一定非常直观,但我也不会对模型或文档产生影响。
我怎样才能让它发挥作用?一切正常,直到命名空间&#34; http://my.url&#34;被介绍了。
答案 0 :(得分:1)
使用您在问题中提供的信息,以下演示代码适用于我:
<强>演示强>
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 {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "example/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Container.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/example/input.xml");
Object result = unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(result, System.out);
}
}
<强>输出强>
<?xml version="1.0" encoding="UTF-8"?>
<ns0:root xmlns:ns0="http://my.url">
<x/>
</ns0:root>