使用XmlPullParser解析xml并在arraylist中添加结果

时间:2011-11-07 11:32:18

标签: android xmlpullparser

<users type="array">
    <user>
       <id>aOlXzSQQKr3749eJe5cbCb</id>
       <login>name1</login>
       <login_name warning="deprecated">name1</login_name>
       <name>Name 1</name>
   </user>
  <user>
       <id>c8QDleB8Or36QseJe5cbLA</id>
       <login>name2</login>
       <login_name warning="deprecated">name2</login_name>
       <name>Nmae 2</name>
 </user>
</users >

嗨,我需要使用XMLPullParser来解析XML,我需要在数组列表中使用名称。我该怎么办,请建议。

感谢。

1 个答案:

答案 0 :(得分:1)

也许这样的事情应该有效:

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new FileReader(XMLFILEPATH));
int eventType = xpp.getEventType();
String lastTag;
while (eventType != XmlPullParser.END_DOCUMENT)
    {
        UserStruct user;

        /*
         * The name of the tag like: <foo> --> foo
         */
        String tagName = xpp.getName();
        /*
         * Opening tag
         */
        if (eventType == XmlPullParser.START_TAG)
        {
            if (tagName.equals("users"))
            {
                // init your ArrayList
                urArrayList.clear();
            } else if (tagName.equals("user"))
            {
                // new user tag opened
                user = new UserStruct();
            } else if(tagName.equals("id")) {
                lastTag = "id";
            }

            /*
             * Closing tag
             */
        } else if (eventType == XmlPullParser.END_TAG)
        {
            if (tagName.equals("user"))
            {
                urArrayList.add(user);
            }
        } else if (eventType == XmlPullParser.TEXT)
        {
            if (lastTag.equals("id"))
            {
                // fill UserSTruct
                // do so for the other tags as well
            }
        }

        eventType = xpp.next();
    }