<students>
<student>
<id type="integer">101</id>
<name>James</name>
<degree>
<id type="integer">1978271</id>
<name>SCJP</name>
</degree>
</student>
<student>
<id type="integer">102</id>
<name>Joseph</name>
<degree>
<id type="integer">1978272</id>
<name>MCST</name>
</degree>
</student>
</students>
Please suggest me how to parse it by XMLPullParser
, I know the concept of XmlPullParser
Start and end End element开发者_开发知识库.
Thanks in advance.
It really depends on what you need the data for. But if you need to extract the data from xml and you have your classes prepared for it (i.e. Student, Degree, etc) you implement something similar to following piece of code.
Assuming, that you have your xml data in dataReader variable as Reader, for testing you may use:
String stringData = "...the data goes here...";
StringReader dataReader = new StringReader (stringData);
The code is as follows (having, Student and Degree classes prepared):
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(dataReader);
int eventType = xpp.getEventType();
List<Student> students = new ArrayList<Student>();
Student lastStudent = null;
Degree lastDegree = null;
String lastStartTag = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
final String startTag = xpp.getName();
if ("student".equalsIgnoreCase(startTag)) {
lastStudent = new Student();
} else if ("degree".equalsIgnoreCase(startTag)) {
lastDegree = new Degree();
// TODO: Implement rest of start tags here...
}
lastStartTag = startTag;
} else if (eventType == XmlPullParser.END_TAG) {
final String endTag = xpp.getName();
if ("student".equalsIgnoreCase(endTag)) {
students.add(lastStudent);
lastStudent = null;
} else if ("degree".equalsIgnoreCase(endTag)) {
student.addDegree(lastDegree);
lastDegree = null;
}
// TODO: Implement rest of end tags here...
} else if (eventType == XmlPullParser.TEXT) {
final String text = xpp.getText();
if ("name".equalsIgnoreCase(lastStartTag)) {
if (lastStudent != null) {
lastStudent.setName(text);
} else if (lastDegree != null) {
lastDegree.setName(text);
}
} else if ("id".equalsIgnoreCase(lastStartTag)) {
if (lastStudent != null) {
lastStudent.setId(Integer.parseInt(text));
} else if (lastDegree != null) {
lastDegree.setId(Integer.parseInt(text));
}
}
// TODO: Implement rest of start tags here
}
eventType = xpp.next();
}
NOTE: this code DOES NOT handle any exceptions. You will have to deal with it on your own.
精彩评论