【问题标题】:Extract only HTML tags and attributes from a html string using Jsoup使用 Jsoup 从 html 字符串中仅提取 HTML 标记和属性
【发布时间】:2020-04-29 22:11:46
【问题描述】:

我只想获取 HTML 内容以及属性并删除文本。

输入字符串:

String html = "<p>An <br/><b></b> <a href='http://example.com/' target=\"h\"> <b> example <a><p></b>this is  the </a> link </p>";

输出

<p><br></br><b></b><a href="http://example.com/" target="h"><b><a><p></p></a></b></a></p>

编辑: google 或 stackoverflow 中的大多数问题仅与删除 html 并仅提取文本有关。我花了大约 3 个小时来了解以下提到的解决方案。所以在这里发布它会帮助其他人

【问题讨论】:

    标签: java html jsoup


    【解决方案1】:

    希望这可以帮助像我这样希望仅从 HTML 字符串中删除文本内容的人。

    输出

    <p><br></br><b></b><a href="http://example.com/" target="h"><b><a><p></p></a></b></a></p>
    
    String html = "<p>An <br/><b></b> <a href='http://example.com/' target=\"h\"> <b> example <a><p></b>this is  the </a> link </p>";
           Traverser traverser = new Traverser();
    
           Document document = Jsoup.parse(html, "", Parser.xmlParser());// you can use the html parser as well. which will add the html tags
    
           document.traverse(traverser);
           System.out.println(traverser.extractHtmlBuilder.toString());
    

    通过附加 node.attributes 将包含所有属性。

        public static class Traverser implements NodeVisitor {
    
            StringBuilder extractHtmlBuilder = new StringBuilder();
    
            @Override
            public void head(Node node, int depth) {
                if (node instanceof Element && !(node instanceof Document)) {
                    extractHtmlBuilder.append("<").append(node.nodeName()).append(node.attributes()).append(">");
                }
            }
    
            @Override
            public void tail(Node node, int depth) {
                if (node instanceof Element && !(node instanceof Document)) {
                    extractHtmlBuilder.append("</").append(node.nodeName()).append(">");
                }
            }
        }
    
    

    另一种解决方案:

     Document document = Jsoup.parse(html, "", Parser.xmlParser());
            for (Element element : document.select("*")) {
                if (!element.ownText().isEmpty()) {
                    for (TextNode node : element.textNodes())
                        node.remove();
                }
            }
            System.out.println(document.toString());
    

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2019-02-07
      • 2013-11-23
      • 1970-01-01
      相关资源
      最近更新 更多