这是我的xml,
<root> <child> <Lunchmenu> <id>2</id> <lunch_date>2013-10-24</lunch_date> <break_name>Lunch</break_name> <class_id/> <school_id>1</school_id> <batch_id/> </Lunchmenu> <Eatable> <id>2</id> <eatable_name>Apples</eatable_name> </Eatable> </child> <child> <Lunchmenu> <id>2</id> <lunch_date>2013-10-24</lunch_date> <break_name>Lunch</break_name> <class_id/> <school_id>1</school_id> <batch_id/> </Lunchmenu> <Eatable> <id>3</id> <eatable_name>Orange</eatable_name> </Eatable> </child>
我需要知道,有没有办法解析上面的 xml 的孩子,因为还有两个单独的标签,比如午餐菜单和可食用的。
- 我正在使用 sax 解析器来解析这个 xml。
- 我知道如何解析具有数据的单个子标签并再次对其进行迭代,但在这里我很困惑如何做到这一点?
- 如果有人知道如何解析它,请提出任何解决方案?
谢谢你
我的解析器类是:SchoolParser.java
公共类 SchoolParser 扩展 DefaultHandler {
private List<School> schoolListData ;
private boolean isSuccess;
private School school;
StringBuilder tempData;
@Override
public void startDocument() throws SAXException {
super.startDocument();
Log.e("StudentListParser","startDocument");
schoolListData = new ArrayList<School>();
}
public List<School> getSchoolListData(){
return schoolListData;
}
@Override
public void startElement(String uri, String localName, String qName,
org.xml.sax.Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equals("School")) {
school = new School();
Log.e("SchoolParser", "-----START----");
}
tempData = new StringBuilder();
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempData.append(new String(ch, start, length));
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equals("School")){
schoolListData.add(school);
Log.d("localName",localName);
}
else if (localName.equals("id")) {
Log.e("id", localName);
school.id = Integer.parseInt(tempData.toString());
} else if (localName.equals("school_name")) {
school.schoolName = tempData.toString();
Log.e("name", localName);
} else if (localName.equals("logo")) {
school.logo = tempData.toString().getBytes();
Log.e("logo", localName);
}else if (localName.equals("phone")) {
school.phn_no = tempData.toString();
Log.e("phn no", localName);
}
else if (localName.equals("School")) {
Log.e("SchoolParser", "----END---");
}
// int size = buffer.length();
// buffer.delete(0, size);
// Log.i("buffer is empty", ""+buffer.toString());
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
isSuccess = false;
Log.e("StudentListParser", "endDocument");
}
}