JAXB - 属性“值”已定义。使用 <jaxb:property> 解决此冲突

2022-08-31 14:09:45

使用 JAXB 生成 XML 绑定类。

该架构基于一组旧版 XML 文件,并包含以下代码段:

<xs:complexType name="MetaType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute type="xs:string" name="Name" />
            <xs:attribute type="xs:string" name="Scheme" />
            <xs:attribute type="xs:string" name="Value" />
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

'Value' 属性与 的 'value' 属性冲突,代码生成失败,并显示错误:xs:string

com.sun.istack.SAXParseException2: Property "Value" is already defined. Use &lt;jaxb:property> to resolve this conflict. 

答案 1

答案在于利用 JAXB 绑定 ():site-template.xjb

<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
          xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
          xmlns:xs="http://www.w3.org/2001/XMLSchema"
          version="2.1">
    <bindings schemaLocation="site-template.xsd" version="1.0">
        <!-- Customise the package name -->
        <schemaBindings>
            <package name="com.example.schema"/>
        </schemaBindings>

        <!-- rename the value element -->
        <bindings node="//xs:complexType[@name='MetaType']">
            <bindings node=".//xs:attribute[@name='Value']">
                <property name="ValueAttribute"/>
            </bindings>
        </bindings>
    </bindings>
</bindings>

XPath 表达式定位节点并对其进行重命名,从而避免命名冲突。

使用此绑定 XML 文件,生成的 Java 类最终具有所需的 (以及 )。getValueAttribute()getValue()


答案 2

如果要避免创建/更改 JAXB 绑定文件,并且不介意对 XSD 进行注释,则可以将 jxb:property 注释添加到属性的定义中,例如:

<xs:complexType name="MetaType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute type="xs:string" name="Name" />
            <xs:attribute type="xs:string" name="Scheme" />
            <xs:attribute type="xs:string" name="Value">
                <!-- rename property generated by JAXB (avoiding "Value" name conflict) -->
                <xs:annotation>
                    <xs:appinfo>
                        <jxb:property name="valueAttribute"/>
                    </xs:appinfo>
                </xs:annotation>
            </xs:attribute>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

对 xs:schema 标记进行适当的添加:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
           jxb:version="2.1">

推荐