ITPub博客

首页 > IT职业 > IT职场 > Java系列:读取XML文件

Java系列:读取XML文件

IT职场 作者:mpsky 时间:2021-09-09 09:10:34 0 删除 编辑
  • 导入jar包
    下载jdom-2.0.6.zip并导入jdom-2.0.6.jar
  • xml源文件
  • 代码实例
package json;

import java.io.*;
import java.util.List;
import org.jdom2.*;
import org.jdom2.input.SAXBuilder;
import org.json.JSONObject;

public class ReadXML {
    public String[]  readXML() {
        String dataPath = "E:\GDKJ\word\sensor\xml\ExecData20180327102411.xml";
        String[] str = new String[0];
        SAXBuilder builder = new SAXBuilder();
        try {
            JSONObject jsonObj = new JSONObject("{}");
            File file = new File(dataPath);
            if (file.isFile() && file.exists()) {
                InputStreamReader in = new InputStreamReader(new FileInputStream(file), "GBK");
                //通过saxBuilder的build方法,将输入流加载到saxBuilder中
                Document document = builder.build(in);
                //通过document对象获取xml文件的根节点
                Element rootElement = document.getRootElement();
                //获取根节点下的子节点的List集合
                List bookList = rootElement.getChildren();
                int i =0;
                str = new String[bookList.size()];
                for (Element book : bookList) {
                    List attrBook = book.getAttributes();
                    // 解析AlarmList的属性集合
                    for (Attribute attr : attrBook) {
                        String attrName = attr.getName();
                        String attrValue = attr.getValue();
                        jsonObj.put(attrName,attrValue);
                    }
                    str[i] = String.valueOf(jsonObj);
                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
  • 输出结果
    图片描述

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1806/viewspace-2799900/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 订餐系统(Dome)
请登录后发表评论 登录
全部评论

注册时间:2019-07-18

  • 博文量
    115
  • 访问量
    14709