XML文件操作(一)

1.SAX解析

//第一步:解析XML的对象
SAXParser parser=SAXParserFactory
.newInstance().newSAXParser();
//第二步:获得XML文件
InputStream isInputStream=getResources()
.openRawResource(R.raw.book);
//第三步:处理器
DefaultHandler def=new DefaultHandler(){
boolean flag=false;
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if(localName.equals("name")){
flag=true;
}
super.startElement(uri, localName, qName, attributes);
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(flag){
Log.i("name", ch.toString());
}
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
super.endElement(uri, localName, qName);
}
};
//第四步:开始解析
try {
parser.parse(isInputStream, def);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

posted @ 2017-05-31 14:53  ~~轩  阅读(141)  评论(0编辑  收藏  举报