JAXBElement is used to preserve the element name/namespace in use cases where enough information is not present in the object model. The most common occurence is with substitution groups:
With Substitution Group:
<?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>
Will generate:
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);
}
}
Without Substitution Group:
If you remove the substitution group:
<?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>
The following class will be generated:
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;
}
}
You may also get a JAXBElement when you unmarshal, compare the following examples:
JAXBElement<Foo>
overFoo
. – Nape