2014-01-16 40 views
3

有沒有辦法使用Jsoup來保留新行(不是< BR>)?如何用Jsoup保留新行?

Document pdsc = Jsoup.connect("http://drafts.bestsiteeditor.com/promoters/dsc1387266263.txt").get(); 
String strText = pdsc.body().ownText(); 

tv.setText(strText); 

TXT文件內容來自表單textarea提交,其中有新行。 謝謝。

+0

貌似jsoup對HTML文檔。你可以使用java.net api獲取這個txt文件內容 – user1455836

+0

我轉換到txt,希望得到那些只是顯示。我之前用html做了很多測試。 – BestSiteEditor

+0

顯然jsoup不依賴資源名稱來猜測它的內容類型 – user1455836

回答

0

在文檔上,我不認爲有一種方法可以返回保留新行的文本。如果您確定要打印的文本節點,則有一個方法:getWholeText(http://jsoup.org/apidocs/org/jsoup/nodes/TextNode.html#getWholeText())。如果你想要整個html,你必須提取所有文本節點(遞歸遍歷文檔)。爲了您的例子(它只有一個文本節點):

Document pdsc = Jsoup.connect("http://drafts.bestsiteeditor.com/promoters/dsc1387266263.txt").get(); 
    System.out.println(((TextNode) pdsc.select("body").first().childNode(0)).getWholeText()); 

一個更通用的解決方案:

private static void prinWholeText(Document doc) { 
    List<TextNode> textNode = getAllTextNodes(doc); 
    for(TextNode tn:textNode){ 
     System.out.println(tn.getWholeText()); 
    } 
} 

private static List<TextNode> getAllTextNodes(Document doc) { 
    List<TextNode> nodes = new ArrayList<>(); 
    allTextNodes(doc, nodes); 
    return nodes; 
} 

private static void allTextNodes(Element element, List<TextNode> nodes) { 
    for(Node child: element.childNodes()){ 
     if(child instanceof TextNode){ 
      nodes.add((TextNode) child); 
     } else{ 
      if(child instanceof Element){ 
       allTextNodes((Element) child, nodes); 
      } 
      //implement others 
     } 
    } 
}