我们使用 JAXB 生成 Java 类,遇到了一些生成的复数方法名称不正确的情况。例如,我们期望的地方getPhysicians
我们正在得到getPhysicien
。我们如何自定义 JAXB 复数特定方法的方式?
架构:
<xs:complexType name="physician">
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
<xs:complexType name="physicianList">
<xs:sequence>
<xs:element name="Physician"
type="physician"
minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
生成的Java代码:
...
public class PhysicianList {
...
@XmlElement(name = "Physician")
protected List<Physician> physicien;
...
public List<Physician> getPhysicien() {
if (physicien == null) {
physicien = new ArrayList<Physician>();
}
return this.physicien;
}
Update
布莱斯已经回答了这个问题。然而,我不喜欢在 XML 模式中混合诸如 JAXB 自定义之类的关注点。因此,对于那些具有相同偏好的人来说,这里有一个 JAXB 绑定文件,它实现了与 Blaise 建议相同的功能,将 JAXB 自定义保留在模式之外:
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.0">
<jaxb:bindings schemaLocation="myschema.xsd">
<jaxb:bindings node="//xs:complexType[@name='physicianList']//xs:element[@name='Physician']">
<jaxb:property name="physicians"/>
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
默认情况下,会为您的模式片段生成以下内容:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "physicianList", propOrder = {
"physician"
})
public class PhysicianList {
@XmlElement(name = "Physician")
protected List<Physician> physician;
public List<Physician> getPhysician() {
if (physician == null) {
physician = new ArrayList<Physician>();
}
return this.physician;
}
}
如果您注释 XML 模式:
<xs:schema
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.1">
<xs:complexType name="physician">
<xs:sequence>
</xs:sequence>
</xs:complexType>
<xs:complexType name="physicianList">
<xs:sequence>
<xs:element name="Physician"
type="physician"
minOccurs="0"
maxOccurs="unbounded">
<xs:annotation>
<xs:appinfo>
<jaxb:property name="physicians"/>
</xs:appinfo>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
然后就可以生成所需的类:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "physicianList", propOrder = {
"physicians"
})
public class PhysicianList {
@XmlElement(name = "Physician")
protected List<Physician> physicians;
public List<Physician> getPhysicians() {
if (physicians == null) {
physicians = new ArrayList<Physician>();
}
return this.physicians;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)