首页 > IT职业 > IT职场 > Java系列:读取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/ ,如需转载,请注明出处,否则将追究法律责任。