Android pull解析xml

待解析的xml 文件:



    
        小明
        明明
    
    
        小红
        红红
    
    
        小亮
        亮亮
    

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 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 pullXml(String fileName) throws IOException, XmlPullParserException {
        List 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;
    }

你可能感兴趣的:(Android pull解析xml)