Uruguay" /> Uruguay" /> Uruguay"/>

How to access xsi:type attribute of a xs:anySimpleType element in xjc generated class?

50 Views Asked by At

I need to marshal and unmarshal XMLs that contains structures like this:

<Parameter>
    <Name>Country</Name>
    <Value xsi:type="xsd:string">Uruguay</Value>
</Parameter>

that are defined in the following schema fragment:

<xs:complexType name="Parameter">
    <xs:sequence>
        <xs:element name="Name">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:maxLength value="256"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
        <xs:element name="Value" type="xs:anySimpleType"/>
    </xs:sequence>
</xs:complexType>

The generated class with xjc for the above schema is the following:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Parameter", propOrder = {
    "name",
    "value"
})
public class Parameter {

    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Value", required = true)
    protected Object value;

    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

As you can see the xsi:type attribute in the Value element is not present in Parameter class. And I need to access it as a business requirement.

I have tried modifying the original schema like this:

<xs:complexType name="ParameterValue">
    <xs:simpleContent>
        <xs:extension base="xs:anySimpleType">
            <xs:attribute name="type" type="xs:string"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>
<xs:complexType name="Parameter">
    <xs:sequence>
        <xs:element name="Name">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:maxLength value="256"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
        <xs:element name="Value" type="ParameterValue"/>
    </xs:sequence>
</xs:complexType>

So the value property in Parameter class is of type ParameterValue that contains both type and actual value. This way I have a getter for the type, but type and value are "decoupled" now. I mean when marshaling, the type have to be set manually and it is not inferred from value.

Is there a better way to deal with anySimpleType elements?

0

There are 0 best solutions below