java读取xml文件内容,转为ztree的形式

java读取xml文件内容,转为ztree的形式,第1张

java读取xml文件内容,转为ztree的形式
@ResponseBody
    @RequestMapping("/getXmlNodes")
    public List getXmlNodes(Long versionId){
        try {
            File file = objectFileService.getFileByVersionId(versionId);
            String s;
            InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
            BufferedReader reader = new BufferedReader(in);
            StringBuffer content = new StringBuffer();
            while ((s = reader.readLine()) != null) {
                content = content.append(s + "rn");
            }
            if (null != reader) {
                reader.close();
            }
            JSonObject jsonObject = XMLUtil.xml2JSonObject(content.toString());
            List zTreeNodeList=new ArrayList<>();
            Integer parent = null;
            test(jsonObject,1, parent, zTreeNodeList, null);
            return zTreeNodeList;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }

    public void test(Object o,Integer index, Integer parent, List nodes, String xkey) {
        if (o instanceof JSONObject) {
            Iterator it = ((JSONObject) o).keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (((JSONObject) o).get(key) instanceof JSonArray
                        || ((JSONObject) o).get(key) instanceof JSONObject) {
                    int nodeId=nodes.size() + 1;
                    if (!(((JSONObject) o).get(key) instanceof JSONArray)) {
                        nodes.add(new ZTreeNode(String.valueOf(nodeId), String.valueOf(parent), key));
                        parent = nodeId;
                    }
                    test(((JSONObject) o).get(key),nodeId, parent, nodes, ((JSONObject) o).get(key) instanceof JSonArray ? key : null);
                }else {
                    Map map = nodes.get(index-1).getAttrMap();
                    if(map==null){
                        map=new HashMap<>();
                    }
                    map.put(key,((JSONObject) o).get(key));
                    nodes.get(index-1).setAttrMap(map);
                }
            }
        } else if (o instanceof JSONArray) {
            JSonArray ja = (JSONArray) o;
            for (Object obj : ja) {
                int nodeId = nodes.size() + 1;
                nodes.add(new ZTreeNode(String.valueOf(nodeId), String.valueOf(parent), xkey));
                test(obj,nodeId, nodeId, nodes, xkey);
            }
        }
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5677027.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存