Creating hashmap/map from XML resources

后端 未结 6 1385
礼貌的吻别
礼貌的吻别 2020-12-02 09:56

I\'m making an application where a web service fetches (amongst other) a bunch of codes from a webservice (I.e BEL, FRA, SWE). During runtime I want to translate these codes

6条回答
  •  温柔的废话
    2020-12-02 10:30

    Also you can define a map in XML, put it in res/xml and parse to HashMap (suggested in this post). If you want to keep key order parse to LinkedHashMap. Simple implementation follows:

    Map resource in res/xml:

    
    
        value1
        value2
        value3
    
    

    Resource parser:

    public class ResourceUtils {
        public static Map getHashMapResource(Context c, int hashMapResId) {
            Map map = null;
            XmlResourceParser parser = c.getResources().getXml(hashMapResId);
    
            String key = null, value = null;
    
            try {
                int eventType = parser.getEventType();
    
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_DOCUMENT) {
                        Log.d("utils","Start document");
                    } else if (eventType == XmlPullParser.START_TAG) {
                        if (parser.getName().equals("map")) {
                            boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);
    
                            map = isLinked ? new LinkedHashMap() : new HashMap();
                        } else if (parser.getName().equals("entry")) {
                            key = parser.getAttributeValue(null, "key");
    
                            if (null == key) {
                                parser.close();
                                return null;
                            }
                        }
                    } else if (eventType == XmlPullParser.END_TAG) {
                        if (parser.getName().equals("entry")) {
                            map.put(key, value);
                            key = null;
                            value = null;
                        }
                    } else if (eventType == XmlPullParser.TEXT) {
                        if (null != key) {
                            value = parser.getText();
                        }
                    }
                    eventType = parser.next();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    
            return map;
        }
    }
    

提交回复
热议问题