Android XML Parse parse(String xmlstr, Class clazz, List fields, List elements, String itemElement)

Here you can find the source of parse(String xmlstr, Class clazz, List fields, List elements, String itemElement)

Description

parse

Declaration

public static List<Object> parse(String xmlstr, Class<?> clazz,
        List<String> fields, List<String> elements, String itemElement) 

Method Source Code

//package com.java2s;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

public class Main {

    public static List<Object> parse(String xmlstr, Class<?> clazz,
            List<String> fields, List<String> elements, String itemElement) {
        List<Object> list = new ArrayList<Object>();
        try {/*  ww  w.  ja  v  a 2 s. co m*/
            XmlPullParser xmlPullParser = Xml.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlstr));
            int event = xmlPullParser.getEventType();

            Object obj = null;

            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                case XmlPullParser.START_TAG:
                    if (itemElement.equals(xmlPullParser.getName())) {
                        obj = clazz.newInstance();
                    }
                    if (obj != null
                            && elements.contains(xmlPullParser.getName())) {
                        setFieldValue(obj, fields.get(elements
                                .indexOf(xmlPullParser.getName())),
                                xmlPullParser.nextText());
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (itemElement.equals(xmlPullParser.getName())) {
                        list.add(obj);
                        obj = null;
                    }
                    break;
                }
                event = xmlPullParser.next();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }

    public static void setFieldValue(Object obj, String propertyName,
            Object value) {
        try {
            Field field = obj.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(obj, value);
        } catch (Exception ex) {
            throw new RuntimeException();
        }
    }
}

Related

  1. parse(File source)
  2. parse(String source)
  3. parse(String xml)
  4. parseResponse(HttpResponse response)
  5. parseTagValue(String xml, String tag, String endTag)
  6. ReadCityCode(Context context, String cityname)
  7. XMLfromString(String xml)