项目中有个接口传递过来一个xml格式字符串,为方便处理,将其转换成hashmap
/**
* 将dom对象转换成hashmap对象(备用函数)
* @param document
* @return
*/
public static HashMap<String,Object> xmlToHashMap(Document document){
Element root=document.getDocumentElement();
NodeList iterator=root.getChildNodes();
Stack<Object> stack=new Stack<Object>();
Integer j=0;
HashMap<String,Object> tmp=new HashMap<String, Object>();
do{
for(;j<iterator.getLength();j++)
{
Node childNode = iterator.item(j);
if(childNode.getNodeType() == Node.ELEMENT_NODE){
if(childNode.getChildNodes().getLength()==1 ){
tmp.put(childNode.getNodeName(), childNode.getTextContent());
}else{
HashMap<String,Object> cc=new HashMap<String, Object>();
tmp.put(childNode.getNodeName(), cc);
stack.push(tmp);
stack.push(j+1);
stack.push(iterator);
tmp=cc;
j=0;
iterator=childNode.getChildNodes();
}
}
}
if(stack.isEmpty()){
break;
}
iterator=(NodeList)stack.pop();
j=(Integer)stack.pop();
tmp=(HashMap<String,Object>)stack.pop();
}while(true);
return tmp;
}