[英]How to save newlines from xml?
當我從以下頁面檢索歌詞時: 此處 ,換行符消失。 我以單個String檢索xml,為簡單起見,我使用子字符串減去歌詞。 當我使用以下代碼打印每個字符時,看不到換行符。
if (response.contains("lyrics_body")) {
lyrics = response.substring(response.indexOf("<lyrics_body>") + 13, response.indexOf("</lyrics_body>"));
StringReader sr = new StringReader(lyrics);
int l;
try {
while ((l = sr.read()) != -1) {
System.out.println(":" + l);
}
} catch (Exception ex) {
}
}
部分輸出:
85 U
104 h
110 n
32
116 t
105 i
115 s
115 s
32
117 u
104 h
110 n
32
116 t
105 i
115 s
115 s
32
117 u
104 h
110 n
32
116 t
105 i
115 s
115 s
32
98 b
97 a
98 b
121 y
68 d
111 o
103 g
32
119 w
105 i
108 l
108 l
.
.
為了清楚起見,我在數字后面添加了單個字符,顯然在“ baby”和“ dog”之間應該有換行符。
如何解析此換行符?
我從某處使用過此來源:
public static String postData(String base, List<BasicNameValuePair> data) throws IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(base);
HttpResponse response = null;
String line = "";
StringBuilder total = new StringBuilder();
HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);
try {
httppost.setEntity(new UrlEncodedFormEntity(data));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
total.append("\n"); //I'VE JUST ADDED THIS LINE
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return full string
return total.toString();
}
顯然,出現問題“我剛剛添加了這一行”的部分就是問題,感謝喬恩讓我看過這段代碼!
將StringReader
包裝在BufferedReader
並使用readLine()
BufferedReader bufferedReader = new BufferedReader(new StringReader(lyrics));
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
// do something with line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.