2011-06-19 23 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 
    }