package com.huawei.xml;

import java.io.InputStream;
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;


/**
* @author Administrator
*
* 测试 sax解析
*
*/
public class TestSAXParser {

public static void main(String[] args) throws Exception{
/**
* 得到工厂
*
* 用工厂得到解析器
*
* 用解析器去解析文件 并注册一个处理器
*
*/

//得到工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
//得到解析器
SAXParser saxParser = factory.newSAXParser();

InputStream in = TestSAXParser.class.getClassLoader().getResourceAsStream("com/cdsxt/resources/Users.xml");

saxParser.parse(in,new Handler());
}
}

class Handler extends DefaultHandler{

/**
* 首先是文档开始 startDocument
* 元素开始startElement
* 字符数据characters
* 元素结束endElement
* 文档结束endDocument
*/

//构建一个存储器
Stack<String> names = new Stack<String>();

@Override
public void startDocument() throws SAXException {
//System.out.println("Handler.startDocument()");
}

@Override
public void endDocument() throws SAXException {
//System.out.println("Handler.endDocument()");
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//System.out.println("Handler.startElement()");
/*System.out.println("----------------");
System.out.println("uri:"+uri);
System.out.println("localName:"+localName);
System.out.println("attributes:"+attributes.getValue("id"));
System.out.println("----------------");*/
//System.out.println("qName:"+qName);
names.push(qName);
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//System.out.println("Handler.endElement()");
names.pop();
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
//System.out.println("Handler.characters()");

if(names.peek().equals("username")){
System.out.println(new String(ch,start,length));
}

}

}