有什么方法可以在运行时决定我想要将 XML 解码到哪个 java 类中?
我尝试用这种方式解码代码 -
public Object unmarshallXml(String xmlReq, String className)
{
String myClass = className+".class";
Object instances = null;
try {
JAXBContext jc = JAXBContext.newInstance( myClass );
Unmarshaller u = jc.createUnmarshaller();
StringBuffer xmlStr = new StringBuffer( xmlReq );
StringReader strReader = new StringReader( xmlStr.toString() );
StreamSource strSource = new StreamSource(strReader);
Object o = u.unmarshal( strSource );
} catch (JAXBException e) {
e.printStackTrace();
}
return instances;
}
但出现此错误 -
" javax.xml.bind.JAXBException: "LookupInstances.class" doesnt contain ObjectFactory.class or jaxb.index"
最佳答案
Can we decide the jaxb class at runtime during unmarshalling?
是的,您只需使用采用 Class
参数的 unmarshal
方法之一即可。
构建JAXBContext
仅仅因为您想要解码 Foo
类,并不一定意味着您可以执行 JAXBContext.createContext(Foo.class)
。这是因为您可能需要其他类,但无法从该类传递访问(ObjectFactory
)就是一个很好的例子。
您可以在包名称上创建 JAXBContext
,但这需要以下其中一项:
- 一个名为
ObjectFactory
的类,用@XmlRegistry
注释,位于该包中,并具有足够的指向模型的指针来提取所有必要的类。如果您从 XML 架构生成模型,这将为您完成。 - 如果您没有上述
ObjectFactory
类,您可以包含一个名为jaxb.index
的文本文件,其中包含回车符分隔的短类名称列表。模型。 - 您的模型中没有其他包。如果存在
JAXBContext
需要从冒号分隔的上下文路径引导,其中包含的每个包都满足上述两个条件之一。
关于java - 我们可以在解码期间在运行时决定 jaxb 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28048779/