用SAX 解析XML文件

前端之家收集整理的这篇文章主要介绍了用SAX 解析XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用SAX解析XML文件

SAX是一个解析速度快并且占用内存少的xml解析器,非常适合用于Android等移动设备。SAX解析XML文件采用的是事件驱动,也就是说,它并不需要解析完整个文档,在按内容顺序解析文档的过程中,SAX会判断当前读到的字符是否合法XML语法中的某部分,如果符合就会触发事件。所谓事件,其实就是一些回调(callback方法,这些方法(事件)定义在ContentHandler接口。下面是一些ContentHandler接口常用的方法

startDocument()

当遇到文档的开头的时候,调用这个方法,可以在其中做一些预处理的工作。

如:

publicvoidstartDocument()throwsSAXException{

persons=newArrayList<Person>();

}

endDocument()

和上面的方法相对应,当文档结束的时候,调用这个方法,可以在其中做一些善后的工作。

startElement(StringnamespaceURI,StringlocalName,StringqName,Attributesatts)

当读到一个开始标签的时候,会触发这个方法namespaceURI就是命名空间,localName是不带命名空间前缀的标签名,qName是带命名空间前缀的标签名。通过atts可以得到所有的属性名和相应的值。

如:

publicvoidstartElement(StringnamespaceURI,Attributesatts)throwsSAXException{

if(localName.equals("person")){

currentPerson=newPerson();

currentPerson.setId(Integer.parseInt(atts.getValue("id")));

}

this.tagName=localName;

}

endElement(Stringuri,Stringname)

这个方法和上面的方法相对应,在遇到结束标签的时候,调用这个方法

如:

publicvoidendElement(Stringuri,Stringname)throwsSAXException{

if(localName.equals("person")){

persons.add(currentPerson);

currentPerson=null;

}

this.tagName=null;

}

characters(char[]ch,intstart,intlength)

这个方法用来处理在XML文件中读到的内容,第一个参数为文件的字符串内容,后面两个参数是读到的字符串在这个数组中的起始位置和长度,使用newString(ch,start,length)就可以获取内容

如:

publicvoidcharacters(char[]ch,intlength)throwsSAXException{

if(tagName!=null){

Stringdata=newString(ch,length);

if(tagName.equals("name")){

this.currentPerson.setName(data);

}elseif(tagName.equals("age")){

this.currentPerson.setAge(Short.parseShort(data));

}

}

}

因为ContentHandler是一个接口,在使用的时候可能会有些不方便,因此,SAX还为其制定了一个Helper类:DefaultHandler,它实现了ContentHandler接口,但是其所有的方法体都为空,在实现的时候,你只需要继承这个类,然后重写相应的方法即可。


publicstaticList<Person>readXML(InputStreaminStream){

try{

SAXParserFactoryspf=SAXParserFactory.newInstance();

SAXParsersaxParser=spf.newSAXParser();//创建解析器

XMLContentHandlerhandler=newXMLContentHandler();

saxParser.parse(inStream,handler);

inStream.close();

returnhandler.getPersons();

}catch(Exceptione){

e.printStackTrace();

}

returnnull;

} 原文链接:https://www.f2er.com/xml/299410.html

猜你在找的XML相关文章