0

I place the local XML file into res/raw and then loads it into InputStreamer object. It works fine and I am able to parse its content.

When I place the same XML into res/xml, I get XmlPullParserException saying it can't find the START tag.

I use this code to fill InputStream object:

 InputStream is = getResources().openRawResource(R.raw.data);

and this line to load the XML from /res/xml:

InputStream is = context.getResources().openRawResource(R.xml.data); 

Why is this happening? If the 2nd approach is the wrong one, what is then the purpose of res/xml?

sandalone
  • 41,141
  • 63
  • 222
  • 338
  • 1
    Don't you mean `R.xml.data` in the second bit of code? – Ken Wolf Jul 08 '13 at 17:15
  • @KenWolf Yes, sorry. Copy/paste oversight. – sandalone Jul 08 '13 at 17:22
  • 1
    `getXML()` doesn't return an InputStream... it returns an XMLResourceParser. http://developer.android.com/reference/android/content/res/Resources.html#getXml(int) – Ken Wolf Jul 08 '13 at 17:23
  • @KenWolf Hm, you are right. I typed the second example from my head :). Anyway, is there a way to read XML from `res/xml` at all? Or this folder has another purpose? All samples I found use `res/raw`. – sandalone Jul 08 '13 at 17:27
  • Answered in an answer :). Couldn't find a definitive tutorial but there are a few around for `XMLResourceParser`. – Ken Wolf Jul 08 '13 at 17:31

2 Answers2

0

getXML() doesn't return an InputStream so I'm not sure how your code compiles. It returns an XMLResourceParser.

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

Return an XmlResourceParser through which you can read a generic XML resource for the given resource ID.

The purpose of /res/xml is it's a handy place to store XML and later parse it! Sometimes you don't need an InputStream :)

Ken Wolf
  • 23,133
  • 6
  • 63
  • 84
0

You can read it like this:

void parseXml(int xmlId){
    Resources res = context.getResources();
    //Xml parserer
    XmlResourceParser parser = res.getXml(xmlResource);

    while (parser.next() != XmlPullParser.END_DOCUMENT) {

         //A start tag is reached
         if(parser.getEventType() == XmlPullParser.START_TAG){

             //Which tag is
             if(parser.getName().equalsIgnoreCase("Name"){
                 //Do something when a <Name> tag is reached
                 //and so on ...
             }
         }

    }
}
Myke Dev
  • 180
  • 9