Java系列:读取XML文件
- 导入jar包
下载jdom-2.0.6.zip并导入jdom-2.0.6.jar - xml源文件
<?xml version="1.0" encoding="utf-8"?>
<Root>
<AlarmList Type="1" Key="0101" Description="瓦斯超限,赶快撤离1"></AlarmList>
<AlarmList Type="1" Key="0102" Description="瓦斯超限,赶快撤离2"></AlarmList>
<AlarmList Type="1" Key="0103" Description="瓦斯超限,赶快撤离3"></AlarmList>
</Root>
- 代码实例
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<Element> bookList = rootElement.getChildren();
int i =0;
str = new String[bookList.size()];
for (Element book : bookList) {
List<Attribute> 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;
}
}
- 输出结果
相关文章