Working with Arbitrary XML Resource Files

Android also allows arbitrary XML files as resources. This approach offers three distinct advantages. First, it provides a quick way to reference these files based on their generated resource IDs. Second, the approach allows you to localize these resource XML files. Third, you can compile and store these XML files on the device efficiently.

XML files that need to be read in this fashion are stored under the /res/xml subdirectory. Here is an example XML file called /res/xml/test.xml:

<rootelem1> <subelem1>

Hello World from an xml sub element </subelem1> </rootelem1>

As it does with other Android XML resource files, the AAPT will compile this XML file before placing it in the application package. You will need to use an instance of XmlPullParser if you want to parse these files. You can get an instance of the XmlPullParser implementation using this code from any context (including activity):

Resources res = activity.getResources(); XmlResourceParser xpp = res.getXml(R.xml.test);

The returned XmlResourceParser is an instance of XmlPullParser, and it also implements java.util.AttributeSet. Listing 3-18 shows a more complete code snippet that reads the test.xml file.

Listing 3-18. Using XmlPullParser private String getEventsFromAnXMLFile(Activity activity)

throws XmlPullParserException, IOException {

StringBuffer sb = new StringBuffer(); Resources res = activity.getResources(); XmlResourceParser xpp = res.getXml(R.xml.test);

int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

if(eventType == XmlPullParser.START_DOCUMENT)

else if(eventType == XmlPullParser.START_TAG)

sb.append("\nStart tag "+xpp.getName());

else if(eventType == XmlPullParser.END_TAG)

else if(eventType == XmlPullParser.TEXT)

eventType = xpp.next(); }//eof-while sb.append("\n******End document"); return sb.toString(); }//eof-function

In Listing 3-18, you can see how to get XmlPullParser, how to use XmlPullParser to navigate the XML elements in the XML document, and how to use additional methods of XmlPullParser to access the details of the XML elements. If you want to run this code, you must create an XML file as shown earlier and call the getEventsFromAnXMLFile function from any menu item or button click. It will return a string, which you can print out to the log stream using the Log.d debug method.

0 0

Post a comment