1.SAX的主要事件處理
方法 |
說明 |
public void startDocument() throws SAXException |
文檔開始 |
public void endDocument() throws SAXException |
文檔結束 |
public void startElement(String uri,String localName,String qName,Attributes attr) throws SAXException |
元素開始,可以取得元素的名稱和元素的全部屬性 |
public void endElement(String uri,String localName,String qName) throws SAXException |
元素結束,可以取得元素的名稱和元素的全部屬性 |
public void characters(char[] ch,int start,int length) throws SAXException |
元素內容 |
2.SAX解析器
public class parserSAX extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
}
@Override
public void endDocument() throws SAXException {
System.out.println("\n 讀取結束...");
}
@Override
public void startElement(String uri, String localName, String name, Attributes attr) throws SAXException {
System.out.print("<");
System.out.print(name);
if (attr != null) {
for (int x = 0; x < attr.getLength(); x++) {
System.out.print(" " + attr.getQName(x)
+ "=\"" + attr.getValue(x) + "\"");
}
}
System.out.print(">");
}
@Override
public void endElement(String uri, String localName, String name) throws
SAXException {
System.out.print("</");
System.out.print(name);
System.out.print(">");
}
@Override
public void characters(char[] ch, int start, int length) throws
SAXException{
System.out.print(new String(ch,start,length));
}
}
3.使用SAX解析器
public class Main {
public static void main(String[] args) throws Exception {
SAXParserFactory fac = SAXParserFactory.newInstance();
SAXParser par = fac.newSAXParser();
par.parse("C:" + File.separator + "SAX.xml", new parserSAX());
}
}