student.xml
<?xml version="1.0" encoding="GBK"?> <students> <student> <name>吴飞</name> <college>java学院</college> <telephone>62354666</telephone> <notes>男,1982年生,硕士,现就读于北京邮电大学</notes> </student> <student> <name>李雪</name> <college>C++学院</college> <telephone>62358888</telephone> <notes>男,1987年生,硕士,现就读于中国农业大学</notes> </student> <student> <name>Jack</name> <college>PHP学院</college> <telephone>66666666</telephone> <notes>我是澳洲人</notes> </student> <student> <name>Lucy</name> <college>Android学院</college> <telephone>88888888</telephone> <notes>我是美国人</notes> </student> </students>
package edu.aeon.xml; 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; /** * [说明]:通过sax解析xml文档 * @author aeon(qq:1584875179) * */ public class SAXXMLParser { public static void main(String[] args) { try { //创建解析工厂 SAXParserFactory saxParserFactory=SAXParserFactory.newInstance(); //通过解析工厂获得解析器 SAXParser saxParser=saxParserFactory.newSAXParser(); //通过自定义的解析格式解析执行xml文档 saxParser.parse("config/student.xml", new myDefaultHandler()); } catch (Exception e) { e.printStackTrace(); } } } class myDefaultHandler 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+">"); } }
结果截图: