Reputation: 1241
The function requires the path
of 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!
Upvotes: 3
Views: 299
Reputation: 1914
The following would work:
InputStream is = context.getAssets().open("xml/file.xml");
Upvotes: 2
Reputation: 7383
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
StringBuilder sw = new StringBuilder();
BufferedReader reader = new BufferedReader( new FileReader(file));
String readline = "";
while ((readline = reader.readLine()) != null) {
sw.append(readline);
}
String string = sw.toString();
Upvotes: 1