JAXB 2.x:如何在不知道目标类的情况下解组XML?

bas*_*ero 7 java jaxb jaxb2 moxy

如果有办法,怎么做,我想知道最优雅的一个.这是一个问题: - 假设你有一个抽象类Z - 你有两个从Z继承的类:名为A和B.

您封送任何实例(A或B),如下所示:

JAXBContext context = JAXBContext.newInstance(Z.class);
Marshaller m = context.createMarshaller();
m.marshal(jaxbObject, ...an outputstream...);
Run Code Online (Sandbox Code Playgroud)

在生成的XML中,您可以看到它是什么类型的实例(A或B).

现在,你如何解散呢?

JAXBContext jc = JAXBContext.newInstance(Z.class);
Unmarshaller u = jc.createUnmarshaller();
u.unmarshal(...an inputstream...)
Run Code Online (Sandbox Code Playgroud)

我得到一个UnmarshalException说

"Exception Description: A descriptor with default root element {<my namespace>}<the root tag, e.g. A or B> was not found in the project]
Run Code Online (Sandbox Code Playgroud)

javax.xml.bind.UnmarshalException"

那么你如何进行解组以便获得Z的实例然后你可以在解组后进行测试,它是什么?例如z instanceof A然后... z实例B然后别的东西......等等

感谢您的任何想法或解决方案.

我使用JRE1.6和MOXy作为JAXB Impl.

bas*_*ero 0

我的问题没有答案!

在任何情况下,您都必须准确地告诉解组器它应该解组到哪个对象。