DOM解析XML文件
程序员文章站
2022-05-29 08:20:59
...
XML文件样例:
<?xml version="1.0" encoding="UTF-8"?>
<students>
<stu>
<name>张三</name>
<age>23</age>
<sex>男</sex>
<love>
<love1>骑行1</love1>
<love2>登山1</love2>
</love>
</stu>
<stu>
<name>李四</name>
<age>22</age>
<sex>女</sex>
</stu>
</students>
Student实体类有3个属性:name、age、sex
java代码解析代码:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParseXml {
public static void main(String[] args) {
//1 获取 factory对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
//2 获取DocumentBuilder对象
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
File file = new File("src//xmlTest//student.xml");
//3 获取Documnet对象
Document document = documentBuilder.parse(file);
//4 获取stu节点对象集合
NodeList nodeList = document.getElementsByTagName("stu");
List<Student> list = new ArrayList<Student>();
for(int i = 0;i<nodeList.getLength();i++){
Student student = new Student();
//5.获得对应的某一个stu对象
Element element = (Element) nodeList.item(i);
//6.通过node取值
String name = element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue().trim();
String sex = element.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue().trim();
String age = element.getElementsByTagName("age").item(0).getFirstChild().getNodeValue().trim();
student.setName(name);
student.setSex(sex);
student.setAge(Integer.parseInt(age));
list.add(student);
//7 获得某一个node节点下的子节点
NodeList nodeList1 = element.getElementsByTagName("love");
for(int j = 0;j < nodeList1.getLength();j++){
Element element1 = (Element) nodeList1.item(j);
String love1 = element1.getElementsByTagName("love1").item(0).getFirstChild().getNodeValue().trim();
String love2 = element1.getElementsByTagName("love2").item(0).getFirstChild().getNodeValue().trim();
System.out.println(love1);
System.out.println(love2);
}
}
System.out.println(list);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解析结果:
上一篇: DOM解析XML文件
下一篇: DOM解析XML文件