package com.example;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
public class Xxx {
public static void main(String[] args) {
// 创建SAXParser解析工厂对象
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
try {
// 创建解析器
SAXParser saxParser = saxParserFactory.newSAXParser();
// 执行parse方法
saxParser.parse("D:/_temp/person.xml", new MyDefaultHandle());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 自定义类继承DefaultHandle类
*/
class MyDefaultHandle 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 + ">");
}
}