Android自定义xml解析

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <Users>
        <User 
            name="jason" 
            age="12" 
            location="Beijing"/>

        <User 
            name="peter" 
            age="18" 
            location="Shanghai"/>
            
    </Users>
</resources>
    /**
     * (从XML配置文件获取第三方模块的属性) 
     * @param fragmentActivity activity
     * @param xmlID xml文件的ID
     * @return List<User> 
     * @throws XmlPullParserException
     * @throws IOException
     */
    public static List<User> getUsersFromXML(FragmentActivity fragmentActivity, int xmlID)
            throws XmlPullParserException, IOException {

        XmlResourceParser xmlParser = fragmentActivity.getResources().getXml(xmlID);

        List<User> users = new ArrayList<User>();

        int eventType = xmlParser.getEventType();

        //不是文件结尾就继续解析
        while (eventType != XmlResourceParser.END_DOCUMENT) {

            switch (eventType) {
                
              //文件的内容的起始标签开始,注意这里的起始标签是ThirdPartyUsers.xml文件
                //里面<ThirdPartyUsers>标签下面的第一个标签ThirdPartyUser    
                case XmlResourceParser.START_TAG:
                    String tagName = xmlParser.getName();
                    if (tagName.endsWith("ThirdPartyUser")) {
                        User user = new User();
                        user.user = xmlParser.getAttributeValue(null, "name");
                        user.age = xmlParser.getAttributeValue(null, "age");
                        user.location = xmlParser.getAttributeValue(null, "location");
                        users.add(user) ;
                    }
                    break;

                case XmlResourceParser.END_TAG:
                    break;

                case XmlResourceParser.TEXT:
                    break;
                default:
                    break;
            }
            eventType= xmlParser.next() ;
        }
        xmlParser.close() ;
        
        return users;
    }

 

posted @ 2015-08-01 23:44  jasonkent27  阅读(632)  评论(0编辑  收藏  举报