一、解析XML文档方式:
1、DOM方式:将整个XML文档读取到内存中,按照XML文件的树状结构图进行解析。
2、SAX方式:基于事件的解析,只需要加载XML中的部分数据,优点是,占用资源更少,内存消耗小。
XML文档:
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<name>张三</name>
<age>20</age>
</student>
<student>
<name>李四</name>
<age>22</age>
</student>
<student>
<name>王五</name>
<age>24</age>
</student>
<student>
<name>赵六</name>
<age>21</age>
</student>
</students>
二、DOM解析方式:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("src/students.xml");
NodeList list = doc.getElementsByTagName("student");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
NodeList stulist = node.getChildNodes();
for (int j = 0; j < stulist.getLength(); j++) {
//在XML中会默认包含一个空元素#text,需要略过
if (stulist.item(j).getNodeName().equals("#text"))
continue;
Node childnode = stulist.item(j);
System.out.println(childnode.getNodeName() + ":" + childnode.getTextContent());
}
}
输出结果:
name:张三
age:20
name:李四
age:22
name:王五
age:24