Tuesday, April 20, 2010

Read XML Resources in Android, using XmlResourceParser: XML parsing interface

XmlResourceParser is the XML parsing interface returned for an XML resource. This is a standard XmlPullParser interface, as well as an extended AttributeSet interface and an additional close() method on this interface for the client to indicate when it is done reading the resource.

In this exercise, we read our own XML Resource (in /res/xml folder) using XmlResourceParser, and display the contents on screen.



First of all, create a folder /res/xml, and our own XML file myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<rootelement1>
<subelement>
Hello XML Sub-Element 1
</subelement>
<subelement>
Hello XML Sub-Element 2
<subsubelement>Sub Sub Element</subsubelement>
</subelement>
</rootelement1>


Modify main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/my_xml"
/>
</LinearLayout>


Finally, modify java code
package com.exercise.AndroidXmlResource;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidXmlResource extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView myXmlContent = (TextView)findViewById(R.id.my_xml);
String stringXmlContent;
try {
stringXmlContent = getEventsFromAnXML(this);
myXmlContent.setText(stringXmlContent);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.myxml);
xpp.next();
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
stringBuffer.append("--- Start XML ---");
}
else if(eventType == XmlPullParser.START_TAG)
{
stringBuffer.append("\nSTART_TAG: "+xpp.getName());
}
else if(eventType == XmlPullParser.END_TAG)
{
stringBuffer.append("\nEND_TAG: "+xpp.getName());
}
else if(eventType == XmlPullParser.TEXT)
{
stringBuffer.append("\nTEXT: "+xpp.getText());
}
eventType = xpp.next();
}
stringBuffer.append("\n--- End XML ---");
return stringBuffer.toString();
}
}


Download the files.

Related Article: A simple RSS reader, using Android's org.xml.sax package.



24 comments:

  1. i wrote the code as given but still i am getting Error as "xml cannot be resolved or is not a field" whr the 2 Quick Fix available are the ones which are to make changes in R.java file....

    the piece of code for ".java" file is::
    ......
    StringBuffer stringBuffer = new StringBuffer();
    Resources res = activity.getResources();
    XmlResourceParser xpp = res.getXml(R.xml.myxml);
    xpp.next();
    ......


    i am using Eclipse Helios and other compatible packages...

    n can v use similar for parsing of ".txt" file??

    ReplyDelete
  2. Hi poojan9118,

    Sorry, I do not fully understand your question!

    Do you means the error is reported by Eclipse?

    R.java is auto-generated by Android SDK, suppose you should not touch it.

    May be you can try to clean the project (Project -> Clean) manually, let the SDK re-generate R.java.

    ReplyDelete
  3. I tried to install Eclipse Helios (Eclipse IDE for Java Developers) on Ubuntu 10.04, it work fine have no problem.

    ReplyDelete
  4. the "myxml.xml" will be an Android XML file or ant other XMl file??

    ReplyDelete
  5. "any" other XML file typing error..

    wen i wrote d code given in d blog in "XMLParser.java" file Eclipse showed me Error "xml cannot be resolved or is not a field"!!!

    Its d error u get wen u r writin d code n set "Auto-Build" on..

    and can v parse ".txt" files as wel???

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. ya its done... now its wrking!!
    thank you..

    can u post me d code to parse the text file its named "hello.txt"???

    which commnad or code shall i use??

    ReplyDelete
  8. parse a text file?

    Sorry, I have no idea about it!

    ReplyDelete
  9. hello poojan9118:

    Do you means display text file inside project?

    Please refer Display text file in /res/raw

    ReplyDelete
  10. thanks!!!
    i got dat code wrkin my project.

    but i hav small doubt:
    can we not have dat .txt name as "11.txt" or "A11.txt"...
    as wen i tried dat i got an error in R.java file itself???

    ReplyDelete
  11. hi Android Er,
    appreciate, I studied by your works.

    but I have one question.

    why was that the 'END TAG' is start by one line under the Texts?
    there is even no "\n"..

    ReplyDelete
  12. hwani: Just for better reading:)

    ReplyDelete
  13. I have to use arraylist fro parsing my xml file.very urgent...

    ReplyDelete
  14. How can modify this program by using xml parsing>

    ReplyDelete
  15. Hi
    I have a question about myxml.xml i use eclipse for run this code but i don know where should i put myxml file ?

    ReplyDelete
  16. hello raheleh,

    Create a /xml folder under /res, your xml file put inside xml.

    /res/xml/myxml.xml

    ReplyDelete
  17. For those that couldn't find R.xml.myxml, check the imports, it must not have the generic import android.R, but your own (if you remove it in Eclipse and press CTRL-SHIFT-O you will see what I mean)

    ReplyDelete
  18. please i want to modify the value of an attribute in the xml file and think you :)

    ReplyDelete
  19. Thanks a lot for the clear explanations !

    ReplyDelete
  20. Hi Android Er,
    if the Xml file that I want to read is on C:? How can I do this?? Thanks a lot

    ReplyDelete
  21. Thank you very much, your code helped me a lot

    ReplyDelete
  22. i am getting error when i add xml file in res folder

    ReplyDelete
  23. I have 8 files to parsing stored in android resources: resources/xml/file1, file2,file...8. How can i prepare solution for it?

    ReplyDelete
  24. Such a nice work.....Its really helpful to me.....Thanks a lot .....i m happy with your code...it is enough for me...it is simple & easy coding for understand & implementation....

    ReplyDelete