首先我的XML文件名为a.xml,路径在项目目录下,内容如下:
实现代码如下:
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.helpers.DefaultHandler;
public class SAXDemo {
public static void test1(){
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
DefaultHandlerDemo defaultHandler = new DefaultHandlerDemo();
parser.parse("a.xml", defaultHandler);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
test1();
}
}
class DefaultHandlerDemo extends DefaultHandler{
@Override
public void startDocument() throws SAXException {
System.out.println("开始解析XML文件。。。");
}
@Override
public void endDocument() throws SAXException {
System.out.println("已解析完成。。。");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("元素名称"+qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println(attributes.getQName(i)+"="+attributes.getValue(i));
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String content = new String(ch, start, length);
System.out.println(content);
}
}
实现效果如下: