I am trying to convert any given xml to hash map. I know this can somehow be done using JAXB. I was trying using jsoup. My code is below
public static Map<String,Object> xmlToMapAll(String xml){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
try{
Document xmlDoc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements eles =xmlDoc.getAllElements();
for(Element ele: eles){
Map<String,Object> mi = new HashMap<String,Object>();
if(ele.children().size()>1){
mi = getChilds(ele.children());
}else{
mi.put(ele.tagName(), ele.ownText());
}
list.add(mi);
//map.putAll(mi);
}
map.put("data", list);
map.put("Status", "SUCCESS");
}catch(Exception ce){
log.error("IndoXMLParseUtil.xmlToMapAll() ce "+IndoUtil.getFullLog(ce));
}
return map;
}
public static Map<String,Object> getChilds(Elements childs){
Map<String,Object> map = new HashMap<String,Object>();
for(Element child: childs){
if(child.children().size()>0){
map = getChilds(child.children());
}else{
map.put(child.tagName(), child.ownText());
}
}
return map;
}
public static void main(String args[]){
String xml="<ExtMessage xmlns=\"com/test/schema/evExtQMainPkgQuotaResp\">
<ExtQMainPkgQuotaResp>
<ServiceNumber>1234567</ServiceNumber>
<Source><a>10</a><b>11</b><a>12</a></Source>
<Status>Success</Status>
<ErrorMessage/><InitialQuota>2621440</InitialQuota>
<UsedQuota>62859.49</UsedQuota>
</ExtQMainPkgQuotaResp> </ExtMessage> ";
Map<String, Object> ds = xmlToMapAll(xml);
System.out.println("IndoXMLParseUtil.main() "+ds);
}
output:
{Status=SUCCESS, data=[{#root=}, {extmessage=}, {errormessage=, b=11, status=Success, a=12, initialquota=2621440, usedquota=62859.49}, {servicenumber=6285770355730}, {b=11, a=12}, {a=10}, {b=11}, {a=12}, {status=Success}, {errormessage=}, {initialquota=2621440}, {usedquota=62859.49}]}
Problem is I am getting repeated data. Also I believe there are always better ideas out here.