<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 吗?
最佳答案
这在 XSD 中是合法的。但是,XJC 已知存在名称冲突问题,您可以 override in the JAXB bindings .在这个答案中 I explained a few days ago how that can be done .解决方案是相同的,尽管您的错误原因不同。
请注意,正如您在评论中提到的,使用什么名称无关紧要,只要您告诉 JAXB 将什么 XSD 元素映射到什么 Java 成员即可。 (反)序列化器将确保这是正确的往返。
类似于:
<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>
您可以将绑定(bind)添加到您的 commandline using the -b
option : xjc -d out -b binding.xml yourschemalocation.xsd
,其中 binding.xml
是上面的文件。
如果您可以控制 XSD 模式,另一种选择是使用 XSD 注释来控制生成的类名,as explained by this answer .
关于java - XSD中是否允许内部元素和上层元素同名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864230/