Ali Al-Hudhud
Ali Al-Hudhud

Reputation: 55

Android Parsing XML file get specific data

I have an android code written in Kotlin to get xml data from xml file

data.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <questions>

        <question>aaa</question>
        <question>bbb</question>
        <question>ccc</question>


    </questions>


</resources>

Kotlin Code which will read the xml file above:

        val _is = resources.openRawResource(+R.xml.data)
        val reader = BufferedReader(InputStreamReader(_is))
        val data = StringBuffer()
        var line = reader.readLine()
        while (line != null) {
            data.append(line!! + "\n")
            line = reader.readLine()
        }
        val resourceData = (data.toString())

I tried to print the value of resourceData and i got this

�������������l��������������������������4����������������������������������������������)������aaa��bbb��ccc��question��      questions��     resources�������������������$������������������������������������������������$������������������������������������������������$����������������������������������������������������������������������������������������������������������������������$��������������������������������������������������������������������������������������������������������������������$��������������������������������������������������������������������������������������������������������������������������������������������������������������������������

How I can only get the data i want depended on the tag ? and is it good way to parse a xml file ?

Upvotes: 2

Views: 1035

Answers (2)

user8959091
user8959091

Reputation:

The problem is that you're treating an xml file like a raw file, by using openRawResource():

val _is = resources.openRawResource(+R.xml.data)

if you only wanted to read the lines of the file (which I doubt) you should have put it in raw folder and use this:

val _is = resources.openRawResource(R.raw.data)

but if you need to parse it like an xml then read this:
https://developer.android.com/reference/android/content/res/XmlResourceParser
finally if you just want the values inside the file then you could create a string array inside strings.xml like this:

<string-array name="questions">
    <item>aaa</item>
    <item>bbb</item>
    <item>ccc</item>
</string-array>

and get it in your activity:

val questions = resources.getStringArray(R.string.questions)

now questions is an array of all the values you need.

Upvotes: 0

Petr Kub&#225;č
Petr Kub&#225;č

Reputation: 1640

You probably should use XmlResourceParser documentation

you can get its instance for xml placed in res/xml folder like this:

val xmlResourceParser: XmlResourceParser = resources.getXml(R.xml.your_xml_file_name)

Upvotes: 1

Related Questions