主程序
package cn.demo;
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.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
//获取到XML中具体的某一个值
public class SaxDemo {
public static void main(String[] args) throws ParserConfigurationException,SAXException,IOException {
//1.创建解析工厂
SAXParserFactory factore = SAXParserFactory.newInstance();
//2.得到解析器
SAXParser sax = factore.newSAXParser();
//3.得到读取器
XMLReader reader = sax.getXMLReader();
//4.设置内容处理器
reader.setContentHandler(new ListXml());
//5.读取XML内容
reader.parse("E:\\MyEclipse10\\XmlSax\\src\\cn\\xml\\MyXml.xml");
}
}
//得到XML的所有内容(继承DefaultHandler,也就等于实现了ContentHandler)
class ListXml extends DefaultHandler{
private String lableTag; //记住当前得到的是什么标签
private int needNum = 2; //记住你想要得到第几个标签的值
private int number; //记住当前得到的第几个标签
// 解析XML的开始标签
@Override
public void startElement(String uri,String localName,String qName,
Attributes atts) throws SAXException {
//解析所有的开始标签
lableTag = qName;
if(lableTag.equals("作者")){
number++;
}
}
// 解析XML的内容
@Override
public void characters(char[] ch,int start,int length)
throws SAXException {
if("作者".equals(lableTag) && needNum == number){
//变成一个字符串输出
System.out.println(new String(ch,start,length));
}
}
// 解析到XML的结束标签
@Override
public void endElement(String uri,String qName)
throws SAXException {
//当解析到结束标签时又把开始标签设置为空,下一次又赋开始标签。
lableTag = null;
}
}
工具类 package cn.Util; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; //SAX解析工具类 public class SaxXmlUtils { public void getSax(Class object,String path) throws ParserConfigurationException,IOException{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser sax = factory.newSAXParser(); XMLReader reader = sax.getXMLReader(); reader.setContentHandler(null); reader.parse(path); } } 原文链接:/xml/298391.html