注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
映射的含义
使用 MOXy 作为您的 JAXB 提供程序(请参阅:http ://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html),您可以使用以下代码:
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Simple.class, OtherClass.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum18029865/input.xml");
Simple simple = (Simple) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(simple, System.out);
}
}
将以下 XML 转换为您的 Java 对象/从您的 Java 对象转换:
<?xml version="1.0" encoding="UTF-8"?>
<simple id="foo" other="bar">Hello World</simple>
映射与 XML Schema 的关系
映射它们的类在 XML 模式中没有真正的表示。由于您使用了@XmlValue注释,结果类型将扩展xsd:string,但您还指出它应该扩展对应于 的复杂类型OtherClass。
JAXB 参考实现的作用
对于完全相同的映射,JAXB RI 在创建JAXBContext. 由于 XML 模式中不允许这种表示形式,因此他们决定不允许在映射中使用这种表示形式。我更喜欢我们在 MOXy 中选择的仍然支持映射的选项。
Exception in thread "main" com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
@XmlValue is not allowed on a class that derives another class.
this problem is related to the following location:
at public java.lang.String forum18029865.Simple.contents
at forum18029865.Simple
at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:102)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:472)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:302)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1140)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:154)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:248)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:235)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:432)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:637)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at forum18029865.Demo.main(Demo.java:9)