hhh3112
hhh3112

Reputation: 2187

Parsing xml files in android

I am developing an android app using code from a normal java application. In this java application i am parsing an XML file which i get like this:

File xmlFile = new File("../project/src/resources/words.xml");

Now in android this doesn't seem to work. I get a file not found exception. I tried to save the file in the res/xml directory but I'm not sure how to get to it.

Can i use the same code to parse the XML as I used for my java application or is there a special way to parse XML files in android?

Upvotes: 2

Views: 801

Answers (2)

Marcos
Marcos

Reputation: 4643

You can do:

InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
... then read the content of the file as a stream ...

Your file must be placed in res/raw/yourfile and resourceId is an integer in R.raw... corresponding to your filename (R.raw.yourfile)

Upvotes: 1

Jason LeBrun
Jason LeBrun

Reputation: 13293

What is ../project/src/resources.words.xml? Is that a pathname in your project directory on your development machine? Of course an Android program is not going to have access to file paths defined on your machine.

If words.xml is a static file that you'd like access to, you should include it in the /res/raw subdirectory of your project. Then you can access it using the methods described in the documentation here:

http://developer.android.com/reference/android/content/res/Resources.html#openRawResource(int)

Or, you can put it in /assets and use this method:

http://developer.android.com/reference/android/content/res/AssetManager.html

Upvotes: 1

Related Questions