Java系列:讀取XML檔案

mpsky發表於2021-09-09
  • 匯入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部落格 ” ,連結:http://blog.itpub.net/1806/viewspace-2799900/,如需轉載,請註明出處,否則將追究法律責任。

相關文章