Ad

Having Trouble Reading Xml File With GetResource().readText()

I'm trying to read different xml files from resources in my project and after searching around for a while I found that getResource().readText() seemed to work fine for most. However, when I try to do it the output is just a bunch of

��������������@�������������������.

I'm not an expert but I guess it has something to do with UTF-8, but I simply can't find the answer.

val fileContent = 
this::class.java.getResource("/res/xml/test.xml").readText(Charsets.UTF_8)

(I've tried both with and without "Charsets.UTF_8")

the xml file i'm trying to read:

<?xml version="1.0" encoding="UTF-8"?><request><getInkLevels/></request>
Ad

Answer

The Class#getResource(String) method you tried is not normally used in Android development. The canonical practice is to use an instance of the Resources class obtained from a Context instance. You can read the developer resources guide to learn more.

Check out this answer to see what I believe is the easiest way to meet your needs.

It suggests to store your XML file under the /res/raw directory and access it at run-time via Resources#openRawResource(int). That method returns an input stream which you can read however works best for you. Some XML parsing libraries might accept an input stream directly. You could also read the stream into a string like so,

import android.content.res.Resources
import androidx.annotation.RawRes

fun readXmlResourceAsString(resources: Resources, @RawRes xmlResId: Int): String =
    resources.openRawResource(xmlResId).use { resourceStream ->
        String(resourceStream.readBytes(), Charsets.UTF_8)
    }

I will also mention that there is a method that sounds like it should better suit your needs, namely Resources#getXml(Int). However, it returns an instance of android.content.res.XmlResourceParser which has quite limited parsing capabilities. I strongly suspect you will find it needlessly difficult to use this class to achieve whatever it is you intend to do with your XML.

Ad
source: stackoverflow.com
Ad