Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a XML file from resources

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>
like image 818
Anand Avatar asked Dec 29 '11 08:12

Anand


People also ask

Which reader reads data from XML file?

This article describes how to use the XmlTextReader class to read the XML data from a file. The XmlTextReader class provides direct parsing and tokenizing of the XML data.

How do I read text in XML?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).

What is fetch data from XML file?

The page uses the XMLHttpRequest (JavaScript) object to fetch the XML file (sample. xml) then parses it in JavaScript and creates the chart. The function that parses the XML response and then uses the data to create the chart is shown below and called myXMLProcessor() (it's the XMLHttpRequest callback function).


2 Answers

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

like image 92
Caner Avatar answered Sep 30 '22 13:09

Caner


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();
        }
like image 45
Akilan Avatar answered Sep 30 '22 13:09

Akilan