加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml TO json(非递归实现)

发布时间:2020-12-16 08:13:34 所属栏目:百科 来源:网络整理
导读:之前的xml文件转化为json是利用json-lib或者递归方式实现的,在效率方面难免有些不足.经过改进,利用栈实现了非递归的方式,首先需要导入dom4j的jar包。 import com.alibaba.fastjson.JSONObject; import org.dom4j.Document; import org.dom4j.DocumentExce

之前的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{
            //获取xml文件
            File file = new File(filename);
            //创建SAXReader对象
            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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读