【问题标题】:JAXB/XJC generates JAXBElement<String> rather than just String (to handle null case)JAXB/XJC 生成 JAXBElement<String> 而不仅仅是 String(处理 null 情况)
【发布时间】:2014-12-20 08:39:52
【问题描述】:

使用 JDK 1.7 附带的 JAXB/xjc (bin\xjc.exe)

这是我的 XSD 的片段:

<xs:complexType name="NameType">
    <xs:sequence>
      <xs:element name="Surname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
      <xs:element name="Firstname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
      <xs:element name="Middlename" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

生成的类显示:

@XmlElementRef(name = "Surname", type = JAXBElement.class, required = false)
protected JAXBElement<String> surname;

public JAXBElement<String> getSurname() {
    return surname;
}
public void setSurname(JAXBElement<String> value) {
    this.surname = value;
}

我知道 JAXB 使用 JAXBElement 来允许 null,但这没有任何意义,因为任何声明为 String 的东西都可以设置为 null。

而且我没有更改 XSD 的选项,因为我的客户宁愿将现有的 XSD 留在生产环境中。

问题:我可以更改代码生成器来生成吗:

@XmlElementRef(name = "Surname", type = String.class, required = false)
protected String surname;

public String getSurname() {
    return surname;
}
public void setSurname(String value) {
    this.surname = value;
}

谢谢 乔尔

【问题讨论】:

    标签: java xml jaxb xsd


    【解决方案1】:

    默认情况下,当 XML 元素既可空又可选时,将生成 JAXBElement。

    <xs:element name="Surname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
    

    这是为了让您可以在以下场景中构造 XML:

    1. 当属性为 null 时,XML 文档中应不存在该元素。
    2. 当属性为JAXBElement 且设置了 nil 标志时,该元素应存在于 XML 中,其值为 xsi:nil="true"。

    要摆脱JAXBElement,您可以将generateElementProperty 选项用作answered by f1sh,,但您将无法同时处理这两种情况。

    更多信息

    查看我对相关问题的回答:

    【讨论】:

    • 感谢布莱斯的帮助。你摇滚先生。
    【解决方案2】:

    检查您是否可以将参数传递给代码生成器 (xjc)。我曾经遇到过同样的问题,但能够通过将generateElementProperty 设置为 false 来解决问题。 Here's how i did it.

    这绝对是 jaxb 代码生成器上的一些选项,应该可以关闭。

    编辑: 根据xjc.exe /?,您可以使用-b 参数加速绑定文件。

    【讨论】:

    • 感谢 F1sh 的帮助。这似乎确实有效。如果有其他问题我会回复。
    • 非常感谢您的评论,经过几天的尝试,它确实为我解决了问题!
    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多