Use any XML Resource Files

Description

In Android we can use arbitrary XML files as resources.

You can access the xml file from its generated resource IDs, by which you can localize these resource XML files.
Therefore you can compile and store these XML files on the device efficiently.

XML files need to be stored under the /res/xml subdirectory.

Example

The following code shows an example XML file called /res/xml/test.xml.


<root>
   <sub>
      Hello World from an xml sub element
   </sub>
</root>

The AAPT compiles this XML file before placing it in the application package.

The following code shows how to use XmlPullParser to parse these files.


Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.test);
//from ww  w  .j  a va 2 s  . c o m
private String getEventsFromAnXMLFile(Activity activity) throws XmlPullParserException, IOException
{
   StringBuffer sb = new StringBuffer();
   Resources res = activity.getResources();
   XmlResourceParser xpp = res.getXml(R.xml.test);

   xpp.next();
   int eventType = xpp.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT)
    {
        if(eventType == XmlPullParser.START_DOCUMENT)
        {
           System.out.println("Start document");
        }
        else if(eventType == XmlPullParser.START_TAG)
        {
           System.out.println("Start tag "+xpp.getName());
        }
        else if(eventType == XmlPullParser.END_TAG)
        {
           System.out.println("End tag "+xpp.getName());
        }
        else if(eventType == XmlPullParser.TEXT)
        {
           System.out.println("Text "+xpp.getText());
        }
        eventType = xpp.next();
    }
    return sb.toString();
}




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS