我正在尝试从sdcard读取xml文件。我需要将它解析为字符串数组。
XML(a.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Timetable">
<item>05:40</item>
<item>06:00</item>
<item>06:16</item>
<item>06:28</item>
<item>06:40</item>
<item>07:16</item>
<item>07:29</item>
<item>07:43</item>
<item>07:55</item>
<item>08:07</item>
<item>08:22</item>
<item>08:34</item>
<item>08:46</item>
<item>08:58</item>
<item>09:10</item>
<item>09:22</item>
<item>09:34</item>
<item>09:46</item>
<item>12:10</item>
<item>12:22</item>
<item>12:34</item>
<item>12:46</item>
</string-array>
</resources>
我试过使用两个不同的函数,但没有一个工作,最后的字符串是空的。
功能1:
public void function(){
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("FindMyBus/a.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
功能2:
public void prueba(){
File file = new File(Environment.getExternalStorageDirectory()
+ "FindMyBus/a.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}
任何人都可以帮助我吗?
答案 0 :(得分:0)
如果需要解析xml文件,则需要使用xml解析器。将它作为单独的字符串,然后将其保存到字符串数组
请点击此链接了解更好
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
当你得到解析后的字符串时,你可以将它添加到数组中。
答案 1 :(得分:0)
如果您的xml在您的应用程序资源中,就像它似乎一样,您可以这样做:
String[] array = getResources().getStringArray(R.array.Timetable);