Skip to content

Instantly share code, notes, and snippets.

@joelmartinez
Created May 10, 2012 20:50
Show Gist options
  • Save joelmartinez/2655811 to your computer and use it in GitHub Desktop.
Save joelmartinez/2655811 to your computer and use it in GitHub Desktop.
Parse an iOS plist with a dict into a java HashMap<String, ArrayList<String>>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>key1</key>
<array>
<string>one</string>
<string>two</string>
</array>
<key>key2</key>
<array>
<string>one</string>
<string>two</string>
</array>
</dict>
</plist>
package cyborg;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
/**
* This class parses an iOS plist with a dict element into a hashmap.
*/
public class XmlMapParser {
private XmlPullParser parser;
public XmlMapVisitor(Context context, int xmlid) {
parser = context.getResources().getXml(xmlid);
}
public HashMap<String, ArrayList<String>> convert() {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
final String KEY = "key", STRING = "string";
try {
parser.next();
int eventType = parser.getEventType();
String lastTag = null;
String lastKey = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
lastTag = parser.getName();
}
else if (eventType == XmlPullParser.TEXT) {
// some text
if (KEY.equalsIgnoreCase(lastTag)) {
// start tracking a new key
lastKey = parser.getText();
}
else if (STRING.equalsIgnoreCase(lastTag)) {
// a new string for the last encountered key
if (!map.containsKey(lastKey)) {
map.put(lastKey, new ArrayList<String>());
}
map.get(lastKey).add(parser.getText());
}
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment