我正在尝试按照指南here将XML文档解组为DynamicEntity。但是当我解组我的XML时,我遇到了ClassCastException。
我的代码如下:
DynamicJAXBContext context = DynamicJAXBContextFactory.createContextFromXSD(DocumentGenerator.class.getClassLoader().getResourceAsStream("myXSD.xsd"), null, null, null);
FileInputStream xmlInputStream = new FileInputStream("C:\\Users\\alexba\\myXML.xml");
Unmarshaller unmarshaller = context.createUnmarshaller();
DynamicEntity statement = (DynamicEntity) unmarshaller.unmarshal(xmlInputStream);
错误是:
javax.xml.bind.JAXBElement cannot be cast to org.eclipse.persistence.dynamic.DynamicEntity
我的pom依赖是:
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.tools.xjc.maven2</groupId>
<artifactId>maven-jaxb-plugin</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<repositories>
我一直在阅读代码并尝试了解Unmarshall如何返回DynamicEntity。
答案 0 :(得分:1)
MOXy会将解组对象包装在JAXBElement
中,其原因与静态模型相同。当对象对应于命名的复杂类型时,通常就是这种情况。
您可以将对象解组为JAXBElement<DynamicEntity>
:
JAXBElement<DynamicEntity> element = (JAXBElement<DynamicEntity>) unmarshaller.unmarshal(xmlInputStream);
DynamicEntity statement = element.getValue();
或利用JAXBIntrospector
:
DynamicEntity statement = (DynamicEntity) JAXBIntrospector.getValue( unmarshaller.unmarshal(xmlInputStream));