簡體   English   中英

使用 Jsoup 從 html 字符串中僅提取 HTML 標簽和屬性

[英]Extract only HTML tags and attributes from a html string using Jsoup

我只想獲取 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 個小時來遇到下面提到的解決方案。 所以把它貼在這里因為它會幫助別人

希望這可以幫助像我這樣希望僅從 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());

暫無
暫無

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

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