2012-03-22 8 views
3

周りタグ:ラップ私は、HTML文書では、この構造を有している、プレーンHTMLテキスト

<p> 
"<em>You</em> began the evening well, Charlotte," said Mrs.&nbsp;Bennet with civil   self–command to Miss Lucas. "<em>You</em> were Mr.&nbsp;Bingley's first choice." 
</p> 

しかし、私はそれを処理できるようにするには、タグにwrapptedする私の「プレーンテキスト」が必要:)

<p> 
    <text>"</text> 
    <em>You</em> 
    <text> began the evening well, Charlotte," said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas. "</text> 
    <em>You</em> 
    <text> were Mr.&nbsp;Bingley's first choice."</text> 
</p> 

これを達成する方法はありますか?私はtagsoupとjsoupを見てきましたが、これを簡単に解決する方法はありません。おそらく、いくつかの派手な正規表現を使用します。

public static Node toTextElement(String str) { 
    Element e = new Element(Tag.valueOf("text"), ""); 
    e.appendText(str); 
    return e; 
} 

public static void replaceTextNodes(Node root) { 
    if (root instanceof TextNode) 
     root.replaceWith(toTextElement(((TextNode) root).text())); 
    else 
     for (Node child : root.childNodes()) 
      replaceTextNodes(child); 
} 

テストコード:

おかげ

答えて

5

は、ここで提案です

String html = "<p>\"<em>You</em> began the evening well, Charlotte,\" " + 
     "said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas." + 
     " \"<em>You</em> were Mr.&nbsp;Bingley's first choice.\"</p>"; 

Document doc = Jsoup.parse(html); 

for (Node n : doc.body().children()) 
    replaceTextNodes(n); 

System.out.println(doc); 

出力:

完全
<html> 
<head></head> 
<body> 
    <p> 
    <text> 
    &quot; 
    </text><em> 
    <text> 
    You 
    </text></em> 
    <text> 
    began the evening well, Charlotte,&quot; said Mrs.&nbsp;Bennet with civil self–command to Miss Lucas. &quot; 
    </text><em> 
    <text> 
    You 
    </text></em> 
    <text> 
    were Mr.&nbsp;Bingley's first choice.&quot; 
    </text></p> 
</body> 
</html> 
+0

作品!ありがとう! Imは実際にこれを使ってキャンバス上でhtmlをペイントとテキストメソッドを使ってレンダリングしようとしています。これは良いスタート方法ですか? :) – Richard

関連する問題