1、为什么使用dom4j解析xml
DOM4J 表现更优秀,具有性能优异、功能强大和极端易用使用
2、所需jar包
dom4j-1.6.1.jar
3、使用方法
<?xml version="1.0" encoding="UTF-8"?> <books id="book" bean="b"> <book name="java"> <author>黄观众</author> <price>10</price> <publisher>中国人民出版社</publisher> </book> <book name="javascript"> <author>任先琪</author> <price>20</price> <publisher>中国人民出版社</publisher> </book> </books>
1 package com; 2 3 import java.io.InputStream; 4 import java.util.Iterator; 5 import java.util.List; 6 7 import org.dom4j.Attribute; 8 import org.dom4j.Document; 9 import org.dom4j.Element; 10 import org.dom4j.io.SAXReader; 11 12 public class ParseXml { 13 14 public static void main(String[] args) throws Exception { 15 SAXReader sax = new SAXReader(); 16 //获取文件流 17 InputStream is = ParseXml.class.getClassLoader().getResourceAsStream("test.xml"); 18 Document doc = sax.read(is); 19 //获取文档跟元素对象 20 Element root = doc.getRootElement(); 21 //获取根元素的名称、属性 22 System.out.println(root.getName()); 23 //获取跟元素中的所有属性 方式一 24 List<Attribute> attrlist = root.attributes(); 25 for(Attribute attr:attrlist){ 26 System.out.println(attr.getName()+":"+attr.getValue()); 27 } 28 //获取跟元素中的所有属性 方式二 29 Iterator<Attribute> it = root.attributeIterator(); 30 while(it.hasNext()){ 31 Attribute attr = it.next(); 32 System.out.println(attr.getName()+":"+attr.getValue()); 33 } 34 //知道属性名称的情形下获取属性 35 System.out.println(root.attributeValue("id")); 36 System.out.println(root.attributeValue("bean")); 37 //获取属性的个数 38 System.out.println(root.attributeCount()); 39 40 /*************************************************/ 41 42 //获取该节点下的所有子元素 方式一 43 List<Element> elelist = root.elements(); 44 for(Element e:elelist){ 45 System.out.println(e.getName()); 46 } 47 //获取该节点下的所有子元素 方式二 48 Iterator<Element> eleit = root.elementIterator(); 49 while(eleit.hasNext()){ 50 Element attr = eleit.next(); 51 System.out.println(attr.getName()); 52 } 53 //知道元素名称的时候获取该元素 54 Element ele = root.element("book"); 55 System.out.println(ele.getName()); 56 //获取元素文本内容 57 String author = ele.elementText("author"); 58 System.out.println(author); 59 //获取元素后获取文本 60 String eletext = ele.element("author").getText(); 61 System.out.println(eletext); 62 //node 63 System.out.println(root.node(1).getName()); 64 System.out.println(root.node(3).getName()); 65 66 } 67 68 }