SAX解析 (解析XML文件)
程序员文章站
2022-05-28 08:03:02
...
public class DHandler extends DefaultHandler{
private List<PersonBean> list;
private PersonBean personBean;
String name;
//将解析完成后的数据返回Activity
public List<PersonBean> getdata(){
return list;
}
//文档的开始
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
//创建集合 初始化数据
list = new ArrayList<PersonBean>();
}
//属性节点开始 qName用来的到每个节点的值
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
//如果遇到的是person的属性节点创建对象
if(qName.equals("person")){
personBean = new PersonBean();
}
name = qName;
}
//文本节点
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
//得到当前的值
String string = new String(ch, start, length);
//如果遇到的是对应的节点就将值存入对应对象里的值
if(name.equals("name")){
personBean.setName(string);
}else if(name.equals("age")){
personBean.setAge(string);
}
}
//结束属性节点
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
name = "";
//如果遇到person结束简单 就将对象存入集合
if(qName.equals("person")){
list.add(personBean);
}
}
//结束文档
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
}
—————–MainActivity代码—————-
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//点击开始解析
public void getsax(View v){
try {
//得到XML文件
InputStream open = getAssets().open("persons.xml");
//得到解析工厂
SAXParserFactory newInstance = SAXParserFactory.newInstance();
//通过解析工厂得到解析器
SAXParser newSAXParser = newInstance.newSAXParser();
//解析当前的XML文件
DHandler dh = new DHandler();
newSAXParser.parse(open, dh);
//接受解析完的数据
List<PersonBean> list = dh.getdata();
//作业 :掌握后 将数据展示在Listview上
Log.i("TAG", list.size()+"");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
———javaBean代码———
public class PersonBean {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
上一篇: SAX解析xml的characters方法被多次调用
下一篇: xml解析--SAX解析