XSD中是否允许内层元素和上层元素重名?
Is it allowed to have the same name of inner and upper elements in XSD?
<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 时,发生错误 "Records is already defined in package"
而且我想知道,我的 XSD 是否有效?我们可以在另一个与其上层元素同名的内部创建 complexType 吗?
这在 XSD 中是合法的。但是,XJC 已知存在名称冲突问题,您可以 override in the JAXB bindings. In this answer 。解决方法是一样的,只是你的错误原因不同。
请注意,正如您在评论中提到的,使用什么名称无关紧要,只要您告诉 JAXB 什么 XSD 元素映射到什么 Java 成员即可。 (de)serializer 将确保这是正确的 round-trippable。
类似于:
<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
option:xjc -d out -b binding.xml yourschemalocation.xsd
,其中 binding.xml
是上面的文件。
如果您可以控制 XSD 模式,另一种选择是使用 XSD 注释来控制生成的类名,as explained by this answer.
<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 时,发生错误 "Records is already defined in package"
而且我想知道,我的 XSD 是否有效?我们可以在另一个与其上层元素同名的内部创建 complexType 吗?
这在 XSD 中是合法的。但是,XJC 已知存在名称冲突问题,您可以 override in the JAXB bindings. In this answer
请注意,正如您在评论中提到的,使用什么名称无关紧要,只要您告诉 JAXB 什么 XSD 元素映射到什么 Java 成员即可。 (de)serializer 将确保这是正确的 round-trippable。
类似于:
<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
option:xjc -d out -b binding.xml yourschemalocation.xsd
,其中 binding.xml
是上面的文件。
如果您可以控制 XSD 模式,另一种选择是使用 XSD 注释来控制生成的类名,as explained by this answer.