xml TO json(非递归实现)

前端之家收集整理的这篇文章主要介绍了xml TO json(非递归实现)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前的xml文件转化为json是利用json-lib或者递归方式实现的,在效率方面难免有些不足.经过改进,利用栈实现了非递归的方式,首先需要导入dom4j的jar包。


  1. import com.alibaba.fastjson.JSONObject;
  2. import org.dom4j.Document;
  3. import org.dom4j.DocumentException;
  4. import org.dom4j.Element;
  5. import org.dom4j.io.SAXReader;
  6.  
  7. import java.io.File;
  8. import java.util.List;
  9. import java.util.Stack;
  10.  
  11. /** * Created by 东方电视台 on 2017/7/28. */
  12. public class xmlTojson {
  13. public static void main(String[] args) throws Exception{
  14. JSONObject result = getJson("test.xml");
  15. System.out.println(result.toString());
  16. }
  17. public static Document readXml(String filename) throws DocumentException {
  18. Document document = null;
  19. try{
  20. //获取xml文件
  21. File file = new File(filename);
  22. //创建SAXReader对象
  23. SAXReader reader = new SAXReader();
  24. //读取文件
  25. document = reader.read(file);
  26. }catch (DocumentException e){
  27. e.printStackTrace();
  28. }
  29. return document;
  30. }
  31. public static JSONObject getJson(String filename) throws Exception {
  32. JSONObject jsonObj = new JSONObject();
  33. try {
  34. Document doc = readXml(filename);
  35. Element root = doc.getRootElement();
  36. Stack<Element> stackElement = new Stack<Element>();
  37. Stack<JSONObject> stackJson = new Stack<JSONObject>();
  38. stackElement.push(root);
  39. stackJson.push(jsonObj);
  40. while (!stackElement.isEmpty()) {
  41. Element element = stackElement.pop();
  42. JSONObject json = stackJson.pop();
  43. List<Element> childList = element.elements();
  44. //判断该节点的子节点下是否为叶子节点
  45. for (Element e : childList) {
  46. //如果子节点为叶子节点
  47. if (e.elements().isEmpty()) {
  48. json.put(e.getName(),e.getText());
  49. } else {
  50. JSONObject jsonNew = new JSONObject();
  51. json.put(e.getName(),jsonNew);
  52. stackElement.push(e);
  53. stackJson.push(jsonNew);
  54. }
  55. }
  56. }
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. return jsonObj;
  61. }
  62. }

猜你在找的XML相关文章