In non-Android java, I used to use:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("res/xml/xml_sample.xml");
Document document = builder.parse(file);
Now in Android the xml seems to get into R.xml.xml_parse, at least it’s defined into the R.java file. However, I can’t seem to access that path to use it as the File constructor argument.
I’ve seen multiple solutions around which involve using getResources() like this one:
However, since this code is in a independent class which is not an Activity, it doesn’t work.
Any help is appreciated.
I think the other answers are ignoring that you want to use this XML (in a DOM) in non-Android specific code.
If you put the XML under res/xml, you can only use the XML pull parser on it, not the DOM parser. Usually that’s what you want, and it’s a lot more efficient, since most of the actual work of parsing is done at .apk build time; but if you need to use a DOM parser, put the XML file in res/raw. You can get an InputStream from a raw resource like this:
and pass the input stream (instead of any kind of File or path) to the DOM parser.
Your other option is to use the pull parser events to build the DOM object, and then use that.