XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<students>
<student id="1001">
<name>张三</name>
<age>18</age>
</student>
<student id="1002">
<name>李四</name>
<age>20</age>
</student>
<student id="1003">
<name>王五</name>
<age>22</age>
</student>
</students>
dom4j解析
package com.atguigu;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.List;
public class ParseXml {
public static void main(String[] args) throws DocumentException {
//创建解析器
SAXReader reader=new SAXReader();
//使用解析器read()方法,将xml文件解析为Document对象
Document document = reader.read("java_web\\day32_xml\\students.xml");
//通过文档对象,获取根元素
Element rootElement = document.getRootElement();
//通过根元素,获取所有子元素
List<Element> elements = rootElement.elements();
for (Element element : elements) {
String id = element.attributeValue("id");
String name = element.elementText("name");
String age = element.elementText("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
}
}
Xpath解析
package com.atguigu;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XpathParseXml {
public static void main(String[] args) throws DocumentException {
//创建解析器
SAXReader reader=new SAXReader();
//通过read()方法,将xml文件解析成Documnet对象
Document document = reader.read("java_web\\day32_xml\\students.xml");
//xpath解析
Element element = (Element) document.selectSingleNode("/students/student[@id='1003']");
//解析属性值
String id = element.attributeValue("id");
//解析属性文本内容
String name = element.elementText("name");
String age = element.elementText("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
}
dom4j和jaxen的jar包