簡體   English   中英

在純HTML文本周圍包裝標簽

[英]Wrap a tag around plain html text

我的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>

但我需要將我的“純文本”包​​含在標簽中,以便能夠處理它:)

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

測試代碼:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM