歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用SAX技術對XML文檔進行解析范例

使用SAX技術對XML文檔進行解析范例

日期:2017/3/1 10:39:59   编辑:Linux編程
package com.jiangqq.xml.sax;
import java.io.File;
import java.util.Stack;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class SaxTest02 {
public static void main(String[] args) throws Exception, SAXException {

SAXParserFactory factory= SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse(new File("student.xml"), new myHandler());
}
}


class myHandler extends DefaultHandler
{
private Stack<String> stack=new Stack<String>();

private String name;
private String gender;
private String age;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
stack.push(qName);
for(int i=0;i<attributes.getLength();i++)
{
String attrName=attributes.getQName(i);
String attrValue=attributes.getValue(i);
System.out.println(attrName+" = "+attrValue);
}
}
@Override
public void characters(char[] ch, int start, int end) throws SAXException {

String tag=stack.peek();
if("姓名".equals(tag))
{
name=new String(ch,start,end);
}
else if("性別".equals(tag))
{
gender=new String(ch,start,end);
}
else if("年齡".equals(tag))
{
age=new String(ch,start,end);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//表示該元素已經解析完畢,需要從棧中彈出
stack.pop();
if("學生".equals(qName))
{
System.out.println("姓名 :"+name);
System.out.println("性別 :"+gender);
System.out.println("年齡 :"+age);
System.out.println(" ");
}
}

}


XML文檔如下:

<?xml version="1.0" encoding="UTF-8"?>
<學生名冊>
<學生 學號="1">
<姓名>張三</姓名>
<性別>男</性別>
<年齡>21</年齡>
</學生>
<學生 學號="2">
<姓名>李四</姓名>
<性別>女</性別>
<年齡>20</年齡>
</學生>
<學生 學號="3">
<姓名>王五</姓名>
<性別>男</性別>
<年齡>23</年齡>
</學生>
</學生名冊>


解析結果如下:

學號 = 1
姓名 :張三
性別 :男
年齡 :21

學號 = 2
姓名 :李四
性別 :女
年齡 :20

學號 = 3
姓名 :王五
性別 :男
年齡 :23

Copyright © Linux教程網 All Rights Reserved