是否允许在XSD中使用相同的内部和上部元素名称?

时间:2015-09-30 10:51:31

标签: java xsd xjc

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Records">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Contract">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="Records">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element type="xs:string" name="General"/>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

从XSD上方生成POJO时,发生错误“已在包中定义记录”

我想知道,我的XSD是否有效?我们可以在另一个内部创建与其上层元素同名的complexType吗?

1 个答案:

答案 0 :(得分:2)

这在XSD中是合法的。但是,XJC已经知道名称冲突的问题,您可以override in the JAXB bindings。在这个答案中I explained a few days ago how that can be done。解决方案是相同的,但错误的原因是不同的。

请注意,正如您在注释中所提到的,只要您告诉JAXB要使用哪个Java成员映射哪些XSD元素,就会使用哪些名称无关紧要。 (de)序列化器将确保这是正确的可循环使用。

类似的东西:

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
               xmlns:xs="http://www.w3.org/2001/XMLSchema"
               version="2.1">
    <jaxb:bindings schemaLocation="yourschemalocation.xsd">
        <jaxb:bindings node="//xs:element[@name='Contract']
            /xs:complexType/xs:sequence/xs:element[@name='Records']
            /xs:complexType">
            <jaxb:class name="NestedRecords"/>
        </jaxb:bindings>
    </jaxb:bindings>
</jaxb:bindings>

您可以将绑定添加到commandline using the -b optionxjc -d out -b binding.xml yourschemalocation.xsd,其中binding.xml是上面的文件。

另一种方法是,如果您可以控制XSD架构,则使用XSD注释来控制生成的类名as explained by this answer

相关问题