前端之家收集整理的这篇文章主要介绍了
xml TO json(非递归实现),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
之前的xml文件转化为json是利用json-lib或者递归方式实现的,在效率方面难免有些不足.经过改进,利用栈实现了非递归的方式,首先需要导入dom4j的jar包。
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.List;
import java.util.Stack;
/** * Created by 东方电视台 on 2017/7/28. */
public class xmlTojson {
public static void main(String[] args) throws Exception{
JSONObject result = getJson("test.xml");
System.out.println(result.toString());
}
public static Document readXml(String filename) throws DocumentException {
Document document = null;
try{
File file = new File(filename);
SAXReader reader = new SAXReader();
document = reader.read(file);
}catch (DocumentException e){
e.printStackTrace();
}
return document;
}
public static JSONObject getJson(String filename) throws Exception {
JSONObject jsonObj = new JSONObject();
try {
Document doc = readXml(filename);
Element root = doc.getRootElement();
Stack<Element> stackElement = new Stack<Element>();
Stack<JSONObject> stackJson = new Stack<JSONObject>();
stackElement.push(root);
stackJson.push(jsonObj);
while (!stackElement.isEmpty()) {
Element element = stackElement.pop();
JSONObject json = stackJson.pop();
List<Element> childList = element.elements();
for (Element e : childList) {
if (e.elements().isEmpty()) {
json.put(e.getName(),e.getText());
} else {
JSONObject jsonNew = new JSONObject();
json.put(e.getName(),jsonNew);
stackElement.push(e);
stackJson.push(jsonNew);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
}