[JAVA] Generate HashMap from XML resource file

res/xml/monsters.xml


<?xml version="1.0" encoding="utf-8"?>
<map linked="true">
    <entry key="4">Geryos</entry>
    <entry key="1">Airou</entry>
    <entry key="5">Rio Leia</entry>
    <entry key="2">Yan Cook</entry>
    <entry key="3">Dos Jaggi</entry>
    <entry key="6">Rio Leus</entry>
</map>

ResourceUtils


public class ResourceUtils {
    private static final String LOG_TAG = "ResourceUtils";

    public static Map<String, String> getHashMapSS(Context context, int resourceId) {
        Map<String, String> map = null;
        String key = null;
        String value = null;

        try {
            XmlResourceParser parser = context.getResources().getXml(resourceId);
            int eventType = parser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                    Log.d(LOG_TAG, "Start document");
                } else if (eventType == XmlPullParser.START_TAG) {
                    if (parser.getName().equals("map")) {
                        boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);
                        map = isLinked ? new LinkedHashMap<String, String>() : new HashMap<String, String>();
                    } else if (parser.getName().equals("entry")) {
                        key = parser.getAttributeValue(null, "key");
                        if (key == null) {
                            parser.close();
                            return null;
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if (parser.getName().equals("entry")) {
                        Log.d(LOG_TAG, "Put " + key + ":[" + value + "]");
                        map.put(key, value);
                        key = null;
                        value = null;
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    if (key != null) {
                        value = parser.getText();
                    }
                }
                eventType = parser.next();
            }
            Log.d(LOG_TAG, "End document");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return map;
    }
}

usage


LinkedHashMap<String, String> monsters = (LinkedHashMap<String, String>) ResourceUtils.getHashMapSS(context, R.xml.monsters);

Recommended Posts

Generate HashMap from XML resource file
Generate kubernentes manifest file from docker-compose.yaml with kompose
Get attributes and values from an XML file in Java
Output XML tree to file
[Java] Generate Data URI from byte string of file contents [Kotlin]