private void saxParseXml() {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File path = Environment.getExternalStorageDirectory();
File fxml = new File(path,"books.xml");
try {
// FileInputStream fis = new FileInputStream(fxml);//可有可无
//1.获取SAXParserFactory对象
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
//2.获取SAXParser对象
SAXParser parser = saxFactory.newSAXParser();
//3.解析xml
parser.parse(fxml,new MyHandler());
for(Book b:books){
Log.d("book", b.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} 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();
}
}
}
class MyHandler extends DefaultHandler{
private Book book;
private String tag;
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
//解析节点内容或空白
if(tag.equals("name")){
book.setName(new String(ch,start,length));
}else if(tag.equals("price")){
book.setPrice(new String(ch,start,length));
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
//结束文档解析
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
//结束节点解析
tag = "";
if(localName.equals("book")){
books.add(book);
}
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
//开始文档解析
books = new ArrayList<Book>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
tag = localName;
//localName --节点名称
//开始节点解析
if(localName.equals("book")){
book = new Book();
book.setId(attributes.getValue("id"));
}
}
}
XML解析(SAX解析)
最新推荐文章于 2021-09-05 20:23:01 发布