JAXBElement 用于在对象模型中不存在足够信息的用例中保留元素名称/命名空间。最常见的情况是替换组:
使用替换组:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
xmlns="http://www.example.org"
elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element ref="anElement"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="anElement" type="xs:string"/>
<xs:element name="aSubstituteElement" type="xs:string" substitutionGroup="anElement"/>
</xs:schema>
将生成:
package org.example;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"anElement"
})
@XmlRootElement(name = "root")
public class Root {
@XmlElementRef(name = "anElement", namespace = "http://www.example.org", type = JAXBElement.class)
protected JAXBElement<String> anElement;
public JAXBElement<String> getAnElement() {
return anElement;
}
public void setAnElement(JAXBElement<String> value) {
this.anElement = ((JAXBElement<String> ) value);
}
}
无替换组:
如果删除替换组:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
xmlns="http://www.example.org"
elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element ref="anElement"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="anElement" type="xs:string"/>
</xs:schema>
将生成以下类:
package org.example;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"anElement"
})
@XmlRootElement(name = "root")
public class Root {
@XmlElement(required = true)
protected String anElement;
public String getAnElement() {
return anElement;
}
public void setAnElement(String value) {
this.anElement = value;
}
}
当您取消元帅时,您还可能获得JAXBElement,比较以下示例: