四、.JDOM 解析 XML 数据

一、JDOM 概述

JDOM 是一种解析 XML 的 Java 工具包,它基于树型结构, 利用纯 Java 的技术对 XML 文档实现解析。所以中适合于 Java
语言

二、JDOM 解析 XML 的步骤

1) 创建一个 SAXBuilder 对象

2) 调用 build 方法,得到 Document 对象(通过 IO 流)

3) 获取根节点

4) 获取根节点的直接子节点的集合

5) 遍历集合

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <books>
 3     <book id="1001">
 4         <name>软件工程</name>
 5         <author>王一一</author>
 6         <price>66</price>
 7     </book>
 8     <book id="1002">
 9         <name>计算机网络</name>
10         <author>乔二二</author>
11         <price>89</price>
12     </book>
13 </books>
 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 import java.util.List;
 5 
 6 import org.jdom.Attribute;
 7 import org.jdom.Document;
 8 import org.jdom.Element;
 9 import org.jdom.JDOMException;
10 import org.jdom.input.SAXBuilder;
11 
12 public class TestJDOM {
13     public static void main(String[] args) throws FileNotFoundException, JDOMException, IOException {
14 //        1)    创建一个SAXBuilder对象
15         SAXBuilder sb=new SAXBuilder();
16 //    2)    调用build方法,得到Document对象(通过IO流)
17         Document doc=sb.build(new FileInputStream("book.xml"));
18 //    3)    获取根节点
19         Element root=doc.getRootElement(); //books元素
20 //    4)    获取根节点的直接子节点的集合
21         List<Element> bookEle=root.getChildren();//book,2个book
22 //    5)    遍历集合,得到book的每一个子节点(子元素)
23         for(int i=0;i<bookEle.size();i++){
24             Element book=bookEle.get(i);
25             //得到属性集合
26             List<Attribute> attList=book.getAttributes();
27             //遍历属性的集合得到每一个属性
28             for (Attribute attr : attList) {
29                 System.out.println(attr.getName()+"\t"+attr.getValue());
30             }
31         }
32         
33         //得到每一个子节点
34         System.out.println("\n-----------------------");
35         for(int i=0;i<bookEle.size();i++){
36             Element book=bookEle.get(i);//得到每一个book节点
37             List<Element> subBook=book.getChildren();
38             //遍历每一个节点,获取节点名称节点值
39             for (Element ele : subBook) {
40                 System.out.println(ele.getName()+"\t"+ele.getValue());
41             }
42             System.out.println("=========================================");
43         }
44 
45     }
46 }

猜你喜欢

转载自www.cnblogs.com/qiaoxin11/p/12705589.html