用JAXP的SAX方式解析XML文件

简单用JAXP的SAX方式(事件驱动)解析XML文件:

用JAXP的SAX方式解析XML文件

文件(1.XML)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<class>
<student>
<name>张三</name>
<sid>111111</sid>
</student>
<student>
<name>李四</name>
<sid>222222</sid>
</student>
</class>

 Java代码

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 JaxpSax {
public static void main(String[] args) throws Exception {
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse("src/1.xml", new MyHandler1());//在控制台打印出XML文件
//parser.parse("src/1.xml", new MyHandler2());//在控制台打印所有学生姓名
}
}
class MyHandler1 extends DefaultHandler{
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.print("<"+qName+">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.print(new String(ch,start,length));
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.print("</"+qName+">");
}
}
class MyHandler2 extends DefaultHandler{ boolean flag=true;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(qName.equals("name")) flag=true;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(flag) System.out.println(new String(ch,start,length));
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("name")) flag=false;
}
}

控制台运行结果:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYEAAAEdCAIAAABln0xLAAAbaElEQVR4nO2dXZAcR33At4qkUqmQyguVqjzlJVVEulTxEE4lziQkBbHjVBA4HzpjC7SWxMHZWAqWLZdTCIe46s4WsrzGEhYxSDbYWGit6PThC8LgYMcI7JhTiDk/5IoyLsODhCQGf5zOOqPLw+zO9vfM7PZMz+79frUl7U5Pz/T0dP+2e2bnf7WlnomiKIqiBx98M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