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.