2011-06-19 44 views
0

當我從此頁檢索歌詞時:here,換行符消失。我在單個String中檢索xml,爲了簡單起見,我使用substring來減去歌詞。當我使用下面的代碼打印每個字符時,不會看到換行符。輸出如何從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 
. 
. 

我已經添加了數字背後的單個字符的清晰度,顯然「寶貝」和「狗」之間應該有一個換行符。

我該如何解析這個換行符?

+3

*如何將元素檢索爲字符串?請提供一個簡短但完整的例子。 –

+2

該XML錯誤。 XML不是空白敏感的;他們需要擺脫他們的新線。向公司抱怨。 – SLaks

+0

已編輯,並找到解決方案。 – nhaarman

回答

1

我用這個源從什麼地方:

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(); 
} 

顯然,它說,部分「我剛剛加入這一行「是問題所在,感謝Jon讓我看看這段代碼!

0

包裹StringReaderBufferedReader和使用readLine()

BufferedReader bufferedReader = new BufferedReader(new StringReader(lyrics)); 

    for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { 
     // do something with line 
    }