我如何使用XMLPull解析来解析来自url的数据
答案 0 :(得分:0)
看看这个Simple tutorial link。例如:
//sample XML
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<id>1</id>
<name>Sachin</name>
<salary>50000</salary>
</employee>
<employee>
<id>2</id>
<name>Nikhil</name>
<salary>60000</salary>
</employee>
</employees>
//Sample Helper Class
public class XmlPullParserHandler {
private List<Employee> employees= new ArrayList<Employee>();
private Employee employee;
private String text;
public List<Employee> getEmployees() {
return employees;
}
public List<Employee> parse(InputStream is) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("employee")) {
// create a new instance of employee
employee = new Employee();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("employee")) {
// add employee object to list
employees.add(employee);
}else if (tagname.equalsIgnoreCase("id")) {
employee.setId(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("name")) {
employee.setName(text);
} else if (tagname.equalsIgnoreCase("salary")) {
employee.setSalary(Float.parseFloat(text));
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
return employees;
}
}
作为您的指定链接,您需要将Start_Tag
更改为owner
,并将End_Tag
更改为name
,age
,email
。这很简单,对吧?