待解析的xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<students>
<student>
<name sex="man">小明</name>
<nickName>明明</nickName>
</student>
<student>
<name sex="woman">小红</name>
<nickName>红红</nickName>
</student>
<student>
<name sex="man">小亮</name>
<nickName>亮亮</nickName>
</student>
</students>
student.java
:
public class Student {
private String name;
private String sex;
private String nickName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
这里暂时将 student.xml
放在在了assets
文件夹中;
解析代码:
try {
List<Student> students = pullXml("student.xml");
Log.d("TAG", "onClick: " + students.size());
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
//.............................................
/**
* assets 中文件名字
*
* @param fileName
* @return
* @throws IOException
* @throws XmlPullParserException
*/
private List<Student> pullXml(String fileName) throws IOException, XmlPullParserException {
List<Student> list = null;
Student student = null;
XmlPullParser parser = Xml.newPullParser();
InputStream inputStream = getResources().getAssets().open(fileName);
parser.setInput(inputStream, "utf-8");
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<>();
break;
case XmlPullParser.START_TAG:
if ("student".equalsIgnoreCase(parser.getName())) {
student = new Student();
} else if ("name".equalsIgnoreCase(parser.getName())) {
String sex = parser.getAttributeValue(null, "sex");
student.setSex(sex);
String name = parser.nextText();
student.setName(name);
} else if ("nickName".equalsIgnoreCase(parser.getName())) {
String nickName = parser.nextText();
student.setNickName(nickName);
}
break;
case XmlPullParser.END_TAG:
if ("student".equalsIgnoreCase(parser.getName())) {
list.add(student);
student = null;
}
break;
}
type = parser.next();
}
inputStream.close();
return list;
}