- I have xml file under ASSETS dir (com.android.project\assets\xml\file.xml).
- I want to call a (following) function to read the xml file and return the contents as String.
-
The function requires the
pathof the file as string. I don’t know how to give the path of the file as string.private String getXML(String path){ String xmlString = null; AssetManager am = this.getAssets(); try { InputStream is = am.open(path); int length = is.available(); byte[] data = new byte[length]; is.read(data); xmlString = new String(data); } catch (IOException e1) { e1.printStackTrace(); } return xmlString; }
The file.xml:
<Items>
<ItemData>
<ItemNumber>ABC</ItemNumber>
<Description>Desc1</Description>
<Price>9.95</Price>
<Weight>10.00</Weight>
</ItemData>
<ItemData>
<ItemNumber>XYZ</ItemNumber>
<Description>"Desc2"</Description>
<Price>19.95</Price>
<Weight>22.22</Weight>
</ItemData>
</Items>
QUESTIONS:
-
How can I call the function
getXML(String path)with a path as string parameter, if my file is located under \assets\xml\file.xml ? -
Finally, Is there any better way of reading XML file as a String?
Thank you!
the path is just the path under the assets directory using forward slash (/)
so assets/x/y.z is referenced as this.getAssets().open(“x/y.z”);
That isnt the correct way to read the data – Inputstream.read isnt garunteed to read all the data it returns the number of bytes read – likely this will work for smaller file but you might get problems with bigger ones.
This is general code i read to to read text files, instead of a FileReader use an InputStreamReader