1.新建一个SAXTest类,继承import org.xml.sax.helpers.DefaultHandler类
1 package com.qiao.SrpingSource; 2 3 import org.xml.sax.Attributes; 4 import org.xml.sax.SAXException; 5 import org.xml.sax.helpers.DefaultHandler; 6 7 public class SAXTest extends DefaultHandler { 8 9 private String currentTag ; 10 11 /** 12 * 开始读取文档,通常做一些初始化工作 13 */ 14 @Override 15 public void startDocument() throws SAXException { 16 System.out.println("----start document ---"); 17 } 18 19 /** 20 * 开始读取节点 21 */ 22 @Override 23 public void startElement(String uri, String localName, String qName, 24 Attributes attributes) throws SAXException { 25 26 System.out.println(qName+" --"); 27 currentTag=qName; 28 if (qName.equals("name")) { 29 //读取属性中的值 30 if (attributes != null) { 31 for (int i = 0; i < attributes.getLength(); i++) { 32 System.out.println(" sss "+attributes.getQName(i)+ " " + attributes.getValue(i)); 33 } 34 } 35 } 36 37 } 38 39 /** 40 * 读取节点中的文本文档 41 */ 42 @Override 43 public void characters(char[] ch, int start, int length) 44 throws SAXException { 45 //当当前结点名称为name时,获取其节点中的内容 46 if(currentTag.equals("name")){ 47 String content = new String(ch,start,length); 48 System.out.println(content); 49 50 } 51 52 } 53 54 /** 55 * 读取节点结束时 56 */ 57 @Override 58 public void endElement(String uri, String localName, String qName) 59 throws SAXException { 60 } 61 62 /** 63 * 读取文档介绍时 64 */ 65 @Override 66 public void endDocument() throws SAXException { 67 68 System.out.println(">> endDocument <<"); 69 70 } 71 }
2.xml文件为
1 <?xml version="1.0" encoding="UTF-8"?> 2 <class> 3 <stu id="001"> 4 <name>Allen</name> 5 <sex>男</sex> 6 <age>20</age> 7 </stu> 8 <stu id="002"> 9 <name>namy</name> 10 <sex>女</sex> 11 <age>18</age> 12 </stu> 13 <stu id="003"> 14 <name>lufy</name> 15 <sex>男</sex> 16 <age>18</age> 17 </stu> 18 </class>
3.调用方法
1 @Test 2 public void test() throws ParserConfigurationException, SAXException{ 3 4 SAXParserFactory factory = SAXParserFactory.newInstance(); 5 SAXParser parser = factory.newSAXParser(); 6 7 SAXTest handler = new SAXTest(); 8 9 try { 10 parser.parse(new File("D:/eclipse/workspace/SpringSource/src/main/resource/test.xml"), handler); 11 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } 15 16 }
4.运行结果
----start document ---
class --
stu --
name --
Allen //读取到的name节点的值
sex --
age --
stu --
name --
namy //读取到的name节点的值
sex --
age --
stu --
name --
lufy //读取到的name节点的值
sex --
age --
>> endDocument <<