For XML, a generally better option is to put the file in res/xml/
, then get an XmlPullParser
for that XML by calling getResources().getXml()
. The XmlPullParser
allows you to work your way through the XML events (new document, new element, etc.) and read in what you need.
For example, given res/xml/words.xml
like this:
<words>
<word value="lorem" />
<word value="ipsum" />
<word value="dolor" />
<word value="sit" />
<word value="amet" />
<word value="consectetuer" />
<word value="adipiscing" />
<word value="elit" />
<word value="morbi" />
<word value="vel" />
<word value="ligula" />
<word value="vitae" />
<word value="arcu" />
<word value="aliquet" />
<word value="mollis" />
<word value="etiam" />
<word value="vel" />
<word value="erat" />
<word value="placerat" />
<word value="ante" />
<word value="porttitor" />
<word value="sodales" />
<word value="pellentesque" />
<word value="augue" />
<word value="purus" />
</words>
you would read them into an ArrayList<String>
like this (from inside an activity, for example):
ArrayList<String> items=new ArrayList<String>();
XmlPullParser xpp=getResources().getXml(R.xml.words);
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType()==XmlPullParser.START_TAG) {
if (xpp.getName().equals("word")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
(there's a try
/catch
block in there too, but I trimmed that out for the sake of simplicity)
The advantage is that XML stored in a res/xml/
can be read in this way about ten times faster than using an XML parser on an InputStream
from res/raw/
, or from a plain file. That's because Google seriously optimized the act of reading in XML from resource directories known to hold XML (res/xml/
, res/layout/
, etc.), partly by pre-compiling the XML in to a "binary XML" format as part of the build process.
The disadvantage is that fewer developers are familiar with XmlPullParser
.