Oleguer Oleguer - 1 month ago 8x
Android Question

Android Studio find xml data file by name

the problem is that I have various XML files with the data that I need for my app and I want to access to read them by the name of the XML file: "fileName.xml" so I can run the pull parser. Since the program only knows which file to load by its name which is given by a string I can't call them using


I have tried things like:

int resID = getResources().getIdentifier("r.id.fileName", "id", getPackageName());

and then call it by this resID... but it doesn't seem to work (resID is always 0) :(

Any ideas?

Thank you!


The best solution from a performance standpoint is to have a mapping in your Java code between some string and the resource ID value:

private static HashMap<String, Integer> RESOURCES=new HashMap<>();

static {
  RESOURCES.put("thingy", R.xml.thingy);
  RESOURCES.put("thingy2", R.xml.thingy2);
  // and so on

Then, you can just call RESOURCES.get() to retrieve the ID value, without having to use the reflection that goes on inside of getIdentifier().

If you really want to use getIdentifier(), then the syntax would be:

int resID = getResources().getIdentifier("fileName", "xml", getPackageName());


  • the first parameter is the base name of the resource
  • the second parameter is the type of the resource, and the files in res/xml/ are not id resources