Извлечение только HTML тегов и атрибутов из строки html с помощью Jsoup - PullRequest
0 голосов
/ 13 января 2020

Я хочу получить только содержимое 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 часов, чтобы найти следующие решения. Так что разместив здесь, это поможет другим

1 Ответ

1 голос
/ 13 января 2020

Надеюсь, это поможет кому-то вроде меня, желающему удалить только текстовое содержимое из строки 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());
...