- 导入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;
}
}
- 输出结果
点击查看更多内容
4人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦