当类型具有同名的属性和元素时,通常会发生此类问题。
架构.xsd
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema"
xmlns:tns="http://www.example.org/schema"
elementFormDefault="qualified">
<element name="foo">
<complexType>
<sequence>
<element name="bar" type="string"/>
</sequence>
<attribute name="bar" type="string"/>
</complexType>
</element>
</schema>
xjc 架构.xsd
当我们尝试从这个 XML 模式生成 Java 模型时,我们会收到以下错误。
parsing a schema...
[ERROR] Property "Bar" is already defined. Use <jaxb:property> to resolve this conflict.
line 11 of file:/Users/bdoughan/Scratch/src/forum16714465/schema.xsd
[ERROR] The following location is relevant to the above error
line 13 of file:/Users/bdoughan/Scratch/src/forum16714465/schema.xsd
绑定.xml
JAXB 绑定文件可用于定制生成的类。在这里,我们将使用它来重命名与属性对应的bar
属性。
<jxb:bindings
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
version="2.1">
<jxb:bindings schemaLocation="schema.xsd">
<jxb:bindings node="//xs:element[@name='foo']/xs:complexType/xs:attribute[@name='bar']">
<jxb:property name="barAttribute"/>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
xjc -b binding.xml schema.xsd
现在,当您生成 Java 类时,您将获得如下类:
package org.example.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"bar"
})
@XmlRootElement(name = "foo")
public class Foo {
@XmlElement(required = true)
protected String bar;
@XmlAttribute(name = "bar")
protected String barAttribute;
public String getBar() {
return bar;
}
public void setBar(String value) {
this.bar = value;
}
public String getBarAttribute() {
return barAttribute;
}
public void setBarAttribute(String value) {
this.barAttribute = value;
}
}