廖雪峰Java14Java操作XML和JSON-1XML-3SAX
SAX:Simple API for XML
- 基于事件的API
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SAXSample {
static final String XML_URL = "http://rss.sina.com.cn/tech/internet/home28.xml";
public static void main(String[] args) throws Exception{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(XML_URL,new MyHandle());
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandle extends DefaultHandler {
void print(Object... objs){
for(Object obj:objs){
System.out.print(obj);
System.out.print(" ");
}
System.out.println();
}
@Override
public void startDocument() throws SAXException{ //开始解析文档时,就会触发startDocument事件
print("start Document");
}
@Override
public void endDocument() throws SAXException{ //解析结束时,会触发endDocument事件
print("end Document");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ //如果遇到一个XML元素,会触发startElement事件
print("start Element:",localName,qName);
}
@Override
public void endElement(String uri,String localName,String qName) throws SAXException{ //元素结束时,会触发endElement事件
print("end Element:",localName,qName);
}
@Override
public void characters(char[] ch,int start,int length) throws SAXException{ //遇到文本,会触发characters事件
print("characters:",new String(ch,start,length));
}
@Override
public void error(SAXParseException e) throws SAXException{ //遇到错误,会触发error事件
print("error:",e);
}
}
总结:
SAX解析XML
- 一种流式解析XML的API
- 通过事件触发,速度快
- 调用方式通过回调获得数据