Created
May 10, 2012 20:50
-
-
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>>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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