【问题标题】:Why does xs:any not autobind with jaxb class?为什么 xs:any 不与 jaxb 类自动绑定?
【发布时间】:2015-09-03 09:45:30
【问题描述】:

我得到了一个xsd,并从中生成了 JaxB 类(例如 ApplicationCustomType)。有些类有一个 xs:any 作为元素。我可以向这些字段添加内容(例如 xs:any)。编组工作得很好。

但是当我试图解组它时 FullContent contentType = XmlObjectHelper.getXmlTypeFromString(contentType, FullContent.class); JaxB 类没有填充来自每个 xs:any 的字段。所有其他字段都按应有的方式填写,但 xs:any 的绑定似乎不起作用。

我读到了serializing-with-jaxb 的答案,看起来几乎一样,我不认为我忘记了什么。 我还尝试添加lax = true,但它再次没有解组我的xml。

我做错了什么或忘记了什么?

public class ApplicationCustomType {

@XmlAnyElement
protected List<Element> any;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();

一个示例 xs:any 元素。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addressAttachment", propOrder = {
    "locale",
    "ourUserId"

})

public class AddressAttachment {

    @XmlElement(required = false)
    protected String locale;

    @XmlElement(required = false)
    protected String ourUserId;
}

ObjectFactory.java

@XmlElementDecl(namespace = "http://***/xsd/addressAttachment/v1", name = "information")
public JAXBElement<AddressAttachment> createAddressAttachment(AddressAttachment value) {
    return new JAXBElement<AddressAttachment>(_AddressAttachment_QNAME, AddressAttachment.class, null, value);
}

我收到的 xml:

<content>
   <applicationCustom>
       <addressAttachment>
          <locale>CH.de</locale>
          <ourUserId>264646337383839</ourUserId>                       
       </addressAttachment>
   </applicationCustom>
</content>

解决方案:

我们在 List 而不是类的顶部使用 (lax = true) 重试了它。

public class ApplicationCustomType {

@XmlAnyElement(lax = true)
protected List<Element> any;

如果使用&lt;Element&gt;&lt;Object&gt; 不会影响结果。使用 Element 时,您实际上不必向编组器提供类。但在这两种情况下,您都需要为对象工厂中的每个 XMLRootclass 添加@XmlElementDecl,以便为每个要添加到 xs:any 列表的对象。

【问题讨论】:

    标签: java xml xsd jaxb unmarshalling


    【解决方案1】:

    尝试像这样使用它:

    @XmlAnyElement
    protected List<Object> any;
    

    看看里面是什么!

    解释在这里:https://dzone.com/articles/jaxbs-xmlanyelementlaxtrue

    您还应该向解组器提供已知的类(AddressAttachment.class...),否则它无法找出 xml 中的内容对吗?

    您的示例中未显示,但应如下所示:

    JAXBContext.newInstance(FullContent.class,AddressAttachment.class ...);
    

    使用 Any 时,根对象本身没有引用。

    与 Jaxb 共度美好时光

    【讨论】:

    • 我已经添加了你的建议,但我仍然有一个空值,你可以在代码和结果的链接中看到。
    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多