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.



22 comments:

poojan9118 said...

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??

Android Er said...

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.

Android Er said...

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

poojan9118 said...

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

poojan9118 said...

"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???

poojan9118 said...
This comment has been removed by the author.
poojan9118 said...

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??

Android Er said...

parse a text file?

Sorry, I have no idea about it!

Android Er said...

hello poojan9118:

Do you means display text file inside project?

Please refer Display text file in /res/raw

poojan9118 said...

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???

hwani said...

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"..

Android Er said...

hwani: Just for better reading:)

Alexx said...

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

Alexx said...

How can modify this program by using xml parsing>

Syed Rakib Al Hasan said...

thanks for this article

raheleh said...

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 ?

Android Er said...

hello raheleh,

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

/res/xml/myxml.xml

Fernando said...

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)

Mkaréz said...

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

Diego said...

Thanks a lot for the clear explanations !

Francesca said...

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

Anonymous said...

Thank you very much, your code helped me a lot