【问题标题】:Wrap a tag around plain html text将标签包裹在纯 html 文本周围
【发布时间】:2012-03-22 12:59:28
【问题描述】:

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

任何想法如何做到这一点?我看过 tagoup 和 jsoup 但我似乎没有办法轻松解决这个问题。也许使用一些花哨的正则表达式。

谢谢

【问题讨论】:

    标签: java regex jsoup text-parsing tag-soup


    【解决方案1】:

    这里有一个建议:

    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>
    

    【讨论】:

    • 完美运行!谢谢!我实际上试图使用它来使用绘制和绘制文本方法在画布上呈现 html。这是一个好的开始方式吗? :)
    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2019-01-28
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多