Reading a XML file from resources

2020-02-08 09:34发布

I have a XML file that I need to parse in the Android SDK.

How can I read the XML file path from resources?

The XML contains:

<Book>
<Chapter>
<NO>   1   </NO>
<Text>  My Lord </Text>
</Chapter> 

<Chapter>
<NO>   1   </NO>
<Text>  My Lord </Text>
</Chapter>
</Book>

3条回答
狗以群分
2楼-- · 2020-02-08 09:41

Before parsing xml create one folder inside your resources and put xml file inside that. And try this code.

try {
            XmlPullParser xpp=getResources().getXml(R.xml.words);

            while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
                if (xpp.getEventType()==XmlPullParser.START_TAG) {
                    if (xpp.getName().equals("word")) {
                        items.add(xpp.getAttributeValue(0));
                    }
                }

                xpp.next();
            }
        }
        catch (Throwable t) {
            Toast
                .makeText(this, "Request failed: "+t.toString(), Toast.LENGTH_LONG)
                .show();
        }
查看更多
Bombasti
3楼-- · 2020-02-08 09:43

If you have an XML file in the raw folder in your resources then you can read it with the following code:

Context context = getApplicationContext();
InputStream istream = context.getResources().openRawResource(R.raw.test);

I hope this is useful to you.

查看更多
家丑人穷心不美
4楼-- · 2020-02-08 10:04

Put it under your_project_root\res\xml\ folder. Then you can open it with:

Resources res = activity.getResources();
XmlResourceParser xrp = res.getXml(R.xml.your_resId);

There is an example on how to use XmlResourceParser here:

http://android-er.blogspot.com/2010/04/read-xml-resources-in-android-using.html

查看更多
登录 后发表回答