1

我使用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;

当我从 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?

4

1 回答 1

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”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));

了解更多信息

我在我的博客上写了更多关于这个特殊用例的文章:

于 2014-05-29T17:07:39.947 回答