I am new to JAXB library and not able to get the solution for adding @XmlAttribute to the existing Code.
I have an XML which have two element (Name and Value) as show below :
<ns4:Envelope xmlns:ns2="xyz/123" xmlns:ns3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns6="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns5="http://www.w3.org/2001/XMLSchema" xmlns:abc="abc">
<ns4:Header>
<ns2:ID ns4:mustUnderstand="1">testId</ns2:ID>
</ns4:Header>
<ns4:Body>
<ns2:Set>
<List ns3:arrayType="abc:hash[1]">
<Struct>
<Name>Interval</Name>
<Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:int">10</Value>
</Struct>
</List>
</ns2:Set>
</ns4:Body>
</ns4:Envelope>
In the above XML, the xsi:type is been getting generated Automatically by JAXB. The Struct Class having the below Code
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Struct", propOrder = {
"name",
"value"
})
public class Struct {
@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 type is not been set in the above class. I want to have some provision to add type as per user defined, rather than getting generated as per the data type.
I am not sure how can I add Attribute to this Struct Class, which can add the type to "Value" Element (As we can see the Value Element is Simple String Object)
If you just want a type
attribute, try something like this:
public class TypedValue {
@XmlAttribute
protected String type;
@XmlValue
protected String value;
}
instead of Object
in Struct.value
.
The xsi:type
is a very special thing for inheritance.
If you want to customize how JAXB represents something you can always create an XmlAdapter
for it.
Adaping a Field/Property
The @XmlJavaTypeAdatper
annotation is used to reference the XmlAdapter
.
@XmlElement(name = "Value", required = true)
@XmlJavaTypeAdapter(ValueAdapter.class)
protected Object value;
XmlAdapter
Is responsible for converting between the real object in your domain model, and the one you want to marshal to get the desired XML.
public class ValueAdapter extends XmlAdapter<MyAdaptedObject, Object> {
...
}
MyAdaptedObject
Is a POJO that will marshal to your desired XML.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.