3

Jsoup で新しい行 (< BR > ではない) を保持する方法はありますか?

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

tv.setText(strText);

TXT ファイルのコンテンツは、新しい行を含むフォーム テキストエリアの送信からのものです。ありがとう。

4

1 に答える 1

0

ドキュメントでは、改行を保持するテキストを返す方法はないと思います。印刷するテキスト ノードを特定する場合は、getWholeText ( http://jsoup.org/apidocs/org/jsoup/nodes/TextNode.html#getWholeText() ) というメソッドがあります。HTML全体が必要な場合は、すべてのテキストノードを抽出する必要があります(ドキュメントの再帰的トラバース)。あなたの例では(テキストノードが1つしかありません):

  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
        }
    }
}
于 2014-06-18T13:19:03.560 に答える