1.通过SAXReader解析(需要导入包:dom4j-1.6.1.jar和jaxen-1.2.0-atlassian-2.jar)
包路径图:
employee.xml文件内容
1 <?xml version="1.0" encoding="UTF-8"?> 2 <emps> 3 <emp> 4 <id>1</id> 5 <name>张三</name> 6 <age>34</age> 7 <gender>男</gender> 8 <salary>3000</salary> 9 </emp> 10 <emp> 11 <id>2</id> 12 <name>李四</name> 13 <age>21</age> 14 <gender>女</gender> 15 <salary>4000</salary> 16 </emp> 17 <emp> 18 <id>3</id> 19 <name>王五</name> 20 <age>46</age> 21 <gender>女</gender> 22 <salary>6500</salary> 23 </emp> 24 <emp> 25 <id>4</id> 26 <name>赵六</name> 27 <age>28</age> 28 <gender>男</gender> 29 <salary>4400</salary> 30 </emp> 31 <emp> 32 <id>5</id> 33 <name>钱七</name> 34 <age>53</age> 35 <gender>男</gender> 36 <salary>12000</salary> 37 </emp> 38 <cmp department="总经办"> 39 <id>007</id> 40 <name>董事长</name> 41 <age>52</age> 42 <gender>男</gender> 43 <salary>100000</salary> 44 </cmp> 45 </emps>
XmlDemo.java代码
1 package xmlDemo; 2 3 import java.io.File; 4 import java.util.List; 5 6 import org.dom4j.Document; 7 import org.dom4j.DocumentException; 8 import org.dom4j.Element; 9 import org.dom4j.io.SAXReader; 10 11 public class XmlDemo { 12 public static void main(String[] args) { 13 try { 14 // 创建SAXReader 15 SAXReader reader = new SAXReader(); 16 Document document = reader.read( 17 new File("C:\\Users\\zouqiang\\Workspaces\\MyEclipse2016\\day1215XML\\src\\xmlDemo\\employee.xml")); 18 // 获取根节点 19 Element root = document.getRootElement(); 20 // 查找指定节点名称QName的所有子节点elements 21 List<Element> list = root.elements("emp"); 22 // 获取emp 23 for (Element object : list) { 24 System.out.println(object.getName()); 25 // System.out.println(object.attribute("department").getData()); 26 for (Element element : (List<Element>) object.elements()) { 27 System.out.print(((Element) element).getName() + ":"); 28 System.out.print(element.getText() + " "); 29 } 30 System.out.println(); 31 } 32 } catch (DocumentException e) { 33 e.printStackTrace(); 34 } 35 } 36 }
输出结果:
emp
id:1 name:张三 age:34 gender:男 salary:3000
emp
id:2 name:李四 age:21 gender:女 salary:4000
emp
id:3 name:王五 age:46 gender:女 salary:6500
emp
id:4 name:赵六 age:28 gender:男 salary:4400
emp
id:5 name:钱七 age:53 gender:男 salary:12000
时间: 2024-10-08 08:40:23