网上找了很多Android解析XML的文章,使用PULL方式解析的基本都是有针对性的解析,这种解析通用性比较差,都是针对自身的项目做针对性的解析,这里自己采用PULL做了一个相对通用的解析方法,代码中共4个方法,两个主函数调用方法,另外两个是针对Map和JSON做的返回节点对象的方法,具体代码如下:
1、转为Map对象
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; private MapxmlToMap(String xml){ Map xmlMap=null; if(xml!=null){ try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(xml)); int eventType=parser.getEventType(); String nodeName=null; Map currentMap=null; List pathList=null; int attributeCount=0; Map tempMap; while (eventType!=XmlPullParser.END_DOCUMENT){ //如果事件类型不等于文档结束事件 String val; switch (eventType){ case XmlPullParser.START_DOCUMENT: { xmlMap = new HashMap<>(); pathList = new ArrayList<>(); Log.e(TAG, "文档开始"); break; } case XmlPullParser.START_TAG: { nodeName = parser.getName(); attributeCount=parser.getAttributeCount(); //属性数量 if(pathList.size()==0){ if(attributeCount>0) { //对元素属性处理 xmlMap.put(nodeName, new HashMap ()); tempMap= (Map ) xmlMap.get(nodeName); for (int index = 0; index < attributeCount ; index++) { //属性关键字默认在关键字前面加入“-”以区分为属性 tempMap.put("-"+parser.getAttributeName(index),parser.getAttributeValue(index)); } }else { xmlMap.put(nodeName, null); } currentMap=xmlMap; }else{ Object obj=getNode(xmlMap, pathList,-1); //获取父节点 String parentKey = pathList.get(pathList.size() - 1);//父关键字 if(obj instanceof HashMap||obj instanceof Map) { currentMap = (Map ) obj; if (currentMap.get(parentKey) == null) { currentMap.put(parentKey, new HashMap ()); } obj=currentMap.get(parentKey); if(obj instanceof HashMap||obj instanceof Map) { currentMap = (Map ) obj; }else if(obj instanceof List|| obj instanceof ArrayList){ ((List) obj).add(new HashMap ()); currentMap= (Map ) ((List) obj).get(((List) obj).size()-1); } }else if(obj instanceof List|| obj instanceof ArrayList){ currentMap = (Map ) ((List) obj).get(((List) obj).size()-1); if(!currentMap.containsKey(parentKey) || currentMap.get(parentKey)==null){ currentMap.put(parentKey,new HashMap ()); } currentMap= (Map ) currentMap.get(parentKey); } if(!currentMap.containsKey(nodeName)){ if(attributeCount>0) { //对属性处理 currentMap.put(nodeName, new HashMap ()); tempMap= (Map ) currentMap.get(nodeName); for (int index = 0; index < attributeCount ; index++) { //属性关键字默认在关键字前面加入“-”以区分为属性 tempMap.put("-"+parser.getAttributeName(index),parser.getAttributeValue(index)); } }else { currentMap.put(nodeName, null); } Log.e(TAG,"元素值为空"); }else{ Log.e(TAG,"元素已经存在,将父节点的值转为列表"); tempMap=currentMap; obj=getNode(xmlMap, pathList,-1); if(obj instanceof Map|| obj instanceof HashMap) { currentMap = (Map ) obj; currentMap.put(parentKey, new ArrayList
2、转为JSON
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
private JSONObject xmlToJSONObject(String xml){
JSONObject xmlJSON=null;
if(xml!=null){
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(xml));
int eventType=parser.getEventType();
String nodeName=null;
JSONObject currentJson=null;
List pathList=null;
int attributeCount=0;
JSONObject tempJson;
while (eventType!=XmlPullParser.END_DOCUMENT) { //如果事件类型不等于文档结束事件
String val;
switch (eventType){
case XmlPullParser.START_DOCUMENT: {
xmlJSON = new JSONObject();
pathList = new ArrayList<>();
Log.e(TAG, "文档开始");
break;
}
case XmlPullParser.START_TAG: {
nodeName = parser.getName();
attributeCount=parser.getAttributeCount(); //属性数量
if(pathList.size()==0){
if(attributeCount>0) { //对元素属性处理
xmlJSON.put(nodeName, new HashMap());
tempJson= (JSONObject) xmlJSON.get(nodeName);
for (int index = 0; index < attributeCount ; index++) {
//属性关键字默认在关键字前面加入“-”以区分为属性
tempJson.put("-"+parser.getAttributeName(index),parser.getAttributeValue(index));
}
}else {
xmlJSON.put(nodeName, null);
}
currentJson=xmlJSON;
}else{
Object obj=getNode(xmlJSON, pathList,-1); //获取父节点
String parentKey = pathList.get(pathList.size() - 1);//父关键字
if(obj instanceof JSONObject) {
currentJson = (JSONObject) obj;
if (currentJson.opt(parentKey) == null) {
currentJson.put(parentKey, new JSONObject());
}
obj=currentJson.opt(parentKey);
if(obj instanceof JSONObject) {
currentJson = (JSONObject) obj;
}else if(obj instanceof JSONArray){
((JSONArray) obj).put(new JSONObject());
currentJson= ((JSONArray) obj).optJSONObject(((JSONArray) obj).length()-1);
}
}else if(obj instanceof JSONArray){
currentJson = ((JSONArray) obj).optJSONObject(((JSONArray) obj).length()-1);
if(!currentJson.has(parentKey) || currentJson.opt(parentKey)==null){
currentJson.put(parentKey,new JSONObject());
}
currentJson= currentJson.optJSONObject(parentKey);
}
if(!currentJson.has(nodeName)){
if(attributeCount>0) { //对属性处理
currentJson.put(nodeName, new JSONObject());
tempJson= currentJson.optJSONObject(nodeName);
for (int index = 0; index < attributeCount ; index++) {
//属性关键字默认在关键字前面加入“-”以区分为属性
tempJson.put("-"+parser.getAttributeName(index),parser.getAttributeValue(index));
}
}else {
currentJson.put(nodeName, null);
}
Log.e(TAG,"元素值为空");
}else{
Log.e(TAG,"元素已经存在,将父节点的值转为列表");
tempJson=currentJson;
obj=getNode(xmlJSON, pathList,-1);
if(obj instanceof JSONObject) {
currentJson = (JSONObject) obj;
currentJson.put(parentKey, new JSONArray());
JSONArray jsonList = currentJson.optJSONArray(parentKey);
jsonList.put(tempJson);
jsonList.put(new JSONObject());
currentJson = jsonList.optJSONObject(jsonList.length() - 1);
if(attributeCount>0) { //对属性处理
currentJson.put(nodeName, new JSONObject());
tempJson= currentJson.optJSONObject(nodeName);
for (int index = 0; index < attributeCount ; index++) {
//属性关键字默认在关键字前面加入“-”以区分为属性
tempJson.put("-"+parser.getAttributeName(index),parser.getAttributeValue(index));
}
}else {
currentJson.put(nodeName, null);
}
}
}
}
pathList.add(nodeName);
Log.e(TAG, nodeName+"元素或节点开始");
break;
}
case XmlPullParser.END_TAG: {
Log.e(TAG, "元素或节点结束");
if(pathList.size()>0) {
int id = pathList.size() - 1;
pathList.remove(id); //删除已完成的路径
if(id>0)
nodeName = pathList.get(id-1);// 获取父节点名称
}
attributeCount=0;
break;
}
case XmlPullParser.TEXT:
case XmlPullParser.CDSECT:
case XmlPullParser.ENTITY_REF: {
val = parser.getText();
Log.e(TAG, "文本、CDATA标记或实体引用开始:" + val);
if (currentJson != null && val != null && !val.equals("n")) {
if(attributeCount==0) {
if(currentJson.opt(nodeName)!=null) {
val=currentJson.opt(nodeName)+val;
}
currentJson.put(nodeName, val);
}else{
Log.e(TAG,"带属性的节点。值:"+val);
tempJson= currentJson.optJSONObject(nodeName);
if(currentJson.opt(nodeName)!=null) {
val=currentJson.opt("#text")+val;
}
tempJson.put("#text",val); //这里固定对带属性节点中包含值默认命名
}
}
break;
}
case XmlPullParser.IGNORABLE_WHITESPACE:
case XmlPullParser.PROCESSING_INSTRUCTION:{
val = parser.getText();
Log.e(TAG,"处理指令:"+val);
if(currentJson.has(nodeName)) { //对处理指令节点处理。遇到处理指令节点删除该节点
currentJson.remove(nodeName);
}
break;
}
}
eventType=parser.nextToken();
}
Log.e(TAG,"解析完成。");
} catch (Exception e) {
e.printStackTrace();
}
}
return xmlJSON;
}
private Object getNode(JSONObject jsonObject, List keyList,int depth){
if (depth>keyList.size() ||depth<0)
depth=keyList.size();
Object obj=jsonObject;
try {
for (int i = 0; i < depth - 1; i++) {
String key = keyList.get(i);
if (obj != null) {
if (obj instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) obj;
obj = jsonArray.opt(jsonArray.length() - 1);
}
if (obj instanceof JSONObject) {
JSONObject jsonTemp=(JSONObject) obj;
if (jsonTemp != null && jsonTemp.length()> 0) {
for (Iterator it = jsonTemp.keys(); it.hasNext(); ) {
String k = it.next();
if (key.equals(k)) {
obj = jsonTemp.opt(k);
break;
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}



