I need to be able to parse large XML files for my particular application (I already had data encoded that way and I wanted to keep it consistant).
So my first attempt was to use getStringArray, which suffers from the problem described in the question:
String [] mDefinitions = getResources().getStringArray(R.array.definition_array);
My second attempt suffers from the same limitation that I encounted with getStringArray. As soon as I tried processing a larger XML file (> 500K), I got a DalvikVM crash on getXml:
XmlResourceParser parser = getResources().getXml(R.xml.index);
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType){
case XmlPullParser.START_TAG:
// handle open tags
break;
case XmlPullParser.END_TAG:
// handle close tags
break;
}
eventType = parser.next();
}
}
catch (XmlPullParserException e) {
throw new RuntimeException("Cannot parse XML");
}
catch (IOException e) {
throw new RuntimeException("Cannot parse XML");
}
finally {
parser.close();
}
My final solution, which uses the SAX parser on a InputStream generated from the raw resource works. I can parse large XML files without the DalvikVM crashing:
InputStream is = getResources().openRawResource(R.raw.index);
XmlHandler myXMLHandler = new XmlHandler();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource (is));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
Where XmlHandler is:
public class XmlHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// handle elements open
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// handle element close
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// handle tag characters <blah>stuff</blah>
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…