I have an XML file. In this file, some of the elements are have attributes that change. I want to put those attributes into a Map. How do I do this?
My XML is:
<ROW id='1'>
<MOBILE>9831138683</MOBILE>
<VARS>
<CAUSE>Delayed payment</CAUSE>
<DO>100.56</DO>
<LOT>1</LOT>
</VARS>
</ROW>
<ROW id='2'>
<MOBILE>9831138684</MOBILE>
<VARS>
<NAME>hi</NAME>
<ADDRESS>Here</ADDRESS>
<LOT>2</LOT>
</VARS>
</ROW>
In this, the VARS
element can have attributes which changes and I do not know beforehand what these elements will be.
I have created a class for this purpose:
@XmlRootElement(name = "ROW")
@XmlAccessorType(XmlAccessType.FIELD)
public class SMSDetail {
@XmlAttribute
private int id;
@XmlElement(name = "MOBILE")
private int mobileNo;
@XmlElement(name = "VARS")
@XmlJavaTypeAdapter(MapAdapter.class)
private HashMap<String, String> variableMap;
public int getId() {
return id;
}
public int getMobileNo() {
return mobileNo;
}
public HashMap<String, String> getVariableMap() {
return variableMap;
}
public void setId(int id) {
this.id = id;
}
public void setMobileNo(int mobileNo) {
this.mobileNo = mobileNo;
}
public void setVariableMap(HashMap<String, String> variableMap) {
this.variableMap = variableMap;
}
}
I want to map the VARS
element to a Map
. I want the tags such as CAUSE
, LOT
to be keys and their values to be the values in the map. I have written an XmlAdapater
for this purpose:
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
public MapAdapter() {
}
@Override
public MapElements[] marshal(Map<String, String> arg0) throws Exception {
MapElements[] mapElements = new MapElements[arg0.size()];
int i = 0;
for (Map.Entry<String, String> entry : arg0.entrySet())
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
return mapElements;
}
@Override
public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
Map<String, String> r = new TreeMap<String, String>();
for (MapElements mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
class MapElements {
@XmlAttribute
public String key;
@XmlAttribute
public String value;
private MapElements() {
} //Required by JAXB
public MapElements(String key, String value) {
this.key = key;
this.value = value;
}
}
This adapter is giving me null
for the variableMap
variable. How should the Adapter be modified for this?