如何正确解组基于模式的请求结果(即xwiki)?

时间:2014-05-29 15:24:19

标签: java xml rest jaxb xwiki

我使用XWiki Schema Definition使用Eclipse XJC Binding Compiler创建了一个对象类模型。在 package-info.java 中,创建了以下命名空间

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.xwiki.org", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.xwiki.rest.model.jaxb;

当我读到Example from an HttpResponse

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<page xmlns="http://www.xwiki.org">
   <link rel="http://www.xwiki.org/rel/space" href="http://localhost:8080/xwiki/rest/wikis/xwiki/spaces/Main" />
   ...
</page>

使用JAXB

try {
   JAXBContext context = JAXBContext.newInstance(org.xwiki.rest.model.jaxb.Page.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   InputStream is = new FileInputStream(new File("request_result.xml"));
   Page page = (Page) unmarshaller.unmarshal(is);
} catch (JAXBException e) {
   e.printStackTrace();
} catch (FileNotFoundException e) {
   e.printStackTrace();
}

异常

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.xwiki.org", local:"page"). Expected elements are <{http://www.xwiki.org}attachments>,<{http://www.xwiki.org}classes>,<{http://www.xwiki.org}comments>,<{http://www.xwiki.org}history>,<{http://www.xwiki.org}objects>,<{http://www.xwiki.org}pages>,<{http://www.xwiki.org}properties>,<{http://www.xwiki.org}searchResults>,<{http://www.xwiki.org}spaces>,<{http://www.xwiki.org}tags>,<{http://www.xwiki.org}wikis>
   at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:648)
   at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
   ...

被抛出。

我不明白错误,因为命名空间似乎是正确的。我需要改变什么才能获得可用的XWiki RESTful API?

1 个答案:

答案 0 :(得分:1)

page元素的映射可能位于生成的@XmlElementDecl类的ObjectFactory注释上。您可以将JAXBContext创建更改为以下内容以进行选择:

JAXBContext context = JAXBContext.newInstance(org.xwiki.rest.model.jaxb.ObjectFactory.class);

或者您可以在生成的模型的包名称上创建JAXBContext

JAXBContext context = JAXBContext.newInstance("org.xwiki.rest.model.jaxb");

更新

  

谢谢,这有点帮助。现在我在线程“main”中得到Exception   java.lang.ClassCastException:javax.xml.bind.JAXBElement不能   强制转换为org.xwiki.rest.model.jaxb.Page。

使用@XmlElementDecl而不是@XmlRootElement注释根时获得的结果是包含域类实例的JAXBElement实例。

您可以执行以下操作:

JAXBElement<Page> jaxbElement = (JAXBElement<Page>) unmarshaller.unmarshal(is);
Page page = jaxbElement.getValue();

或者:

Page page = (Page) JAXBIntrospector.getValue(unmarshaller.unmarshal(is));

了解更多信息

我在博客上写了更多关于这个特定用例的内容: