日期:2014-05-17 浏览次数:20675 次
package cn.xushuai.sax; <?xml version="1.0" encoding="UTF-8" standalone="no"?><exam> <student examid="1111" idcard="0001"> <name>张三</name> <location>北京</location> <grade>90</grade> </student> <student examid="2222" idcard="0002"> <name>李四</name> <location>上海</location> <grade>93</grade> </student> import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class saxReader2 { public static void main(String args) throws ParserConfigurationException, SAXException, IOException { // TODO Auto-generated constructor stub //1.创建解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //2.获取解析器 SAXParser sp = factory.newSAXParser(); //3.得到读取器 XMLReader reader = sp.getXMLReader(); //4.设置内容处理器 reader.setContentHandler(new TagValueHandler()); //5.读取xml文档内容 reader.parse("src/exam.xml"); } class TagValueHandler extends DefaultHandler{ private String currentTag; private int neednumber = 2; private int currentNumber=0; @Override public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { currentTag = arg2; if(currentTag.equals("作者")) currentNumber++; } @Override public void characters(char[] arg0, int arg1, int arg2) throws SAXException { if("作者".equals(currentTag)&& currentNumber==neednumber){ System.out.println(new String(arg0,arg1,arg2)); } } @Override public void endElement(String arg0, String arg1, String arg2) throws SAXException { currentTag= null; } } }