📅  最后修改于: 2023-12-03 15:34:49.026000             🧑  作者: Mango
SAX (Simple API for XML)是一种基于事件驱动的XML解析器,它扫描XML文档并按照元素的顺序触发一系列的事件,应用程序在处理完一个事件后,SAX解析器则丢弃它,继续扫描下一个元素,从而实现高效的XML解析。
import java.io.File;
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 CreateXMLUsingSAXParser {
public static void main(String[] args) {
try {
//创建SAXParserFactory对象
SAXParserFactory factory = SAXParserFactory.newInstance();
//创建SAXParser对象
SAXParser parser = factory.newSAXParser();
//创建MyHandler对象
MyHandler handler = new MyHandler();
//读取xml文件
parser.parse(new File("example.xml"), handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.print("<" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.print(" " + attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\"");
}
System.out.print(">");
}
@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 + ">");
}
@Override
public void endDocument() throws SAXException {
System.out.println();
}
}