微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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{
            //获取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;
    }
}

原文地址:https://www.jb51.cc/xml/293965.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。