Android 读取XML的两种方法。

SAX

SAXParserFactory factory = SAXParserFactory.newInstance();
            // 通过工厂对象得到一个解析器对象
            SAXParser parser = factory.newSAXParser();
            // 通过parser得到XMLReader对象
            XMLReader reader = parser.getXMLReader();
            // 为reader对象注册事件处理接口
            ParseXmlSAX handler = new ParseXmlSAX();
            reader.setContentHandler(handler);
            // 解析指定XML字符串对象
            reader.parse(new InputSource());


XmlResourceParser

XmlResourceParser xml = this.getResources().getXml(R.xml.user);
        users = this.getUserInfo(xml);

xml文件放在 res/xml/路径下

private ArrayList<User> getUserInfo(XmlResourceParser xml)
    {
        ArrayList<User> users = new ArrayList<User>(); 
        User user = null;
        try
        {
            while (xml.getEventType() != XmlResourceParser.END_DOCUMENT)
            {
                
                if (xml.getEventType() == XmlResourceParser.START_TAG)
                {
                    
                    String tagname = xml.getName();
                    if (tagname.endsWith("user"))
                    {
                        user = new User();
                        user.setId(Integer.parseInt(xml.getAttributeValue(null,
                                "id")));
                        user.setName(xml.getAttributeValue(null, "name"));
                        user.setPassword(xml
                                .getAttributeValue(null, "password"));
                        
                        users.add(user);
                    }
                    
                }
                // 下面的两个else if什么作用呢?
                else if (xml.getEventType() == XmlResourceParser.END_TAG)
                {
                } else if (xml.getEventType() == XmlResourceParser.TEXT)
                {
                }
                xml.next();
            }
            // 程序细节注意的地方,StringBuilder要条用toString()方法,不要粗心忘记了
        } catch (XmlPullParserException e)
        {
            return null;
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            return null;
        }
        return users;
    }





你可能感兴趣的:(android,xml)