如何删除那些 html 元素,同时保留格式?

How can I remove those html elements, while retain the formatting?

我已尝试实现 java 邮件 api 以读取邮件正文并将其存储到文本文件中(如果它包含内容)。

我可以阅读邮件正文,但它带有一些 html 元素。

我添加了下面我使用过的代码。

Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");

    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("hostname", "username", "password");
    String result = null;
    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_ONLY);
    javax.mail.Message messages[]=inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
    for(Message message:messages) {
        System.out.println(Jsoup.parse(message).text());
    }

如何删除检索到的消息中的那些 html 元素?

请任何人帮助我解决这个问题。

要删除邮件中的所有 HTML 标签,请使用 jsoups text() 方法。

示例代码

String htmlString = "<div class=\"WordSection1\"> <p class=\"MsoNormal\">Hi<br> <br> <br> <br> Data is written in this mail.<br> <br> <br> <br> <o:p></o:p></p> </div>";

System.out.println(Jsoup.parse(htmlString).text());

输出

Hi Data is written in this mail.

如果特定元素应导致 换行符 类似于呈现的 HTML 源代码,您可以添加换行符,然后添加 avoid pretty printing it, when you jsoups' clean method

prettyPrint

If disabled, the HTML output methods will not re-format the output, and the output will generally look like the input.

示例代码

String htmlString = "<div class=\"WordSection1\"> <p class=\"MsoNormal\">Hi<br> <br> <br> <br> Data is written in this mail.<br> <br> <br> <br> <o:p></o:p></p> </div>";

htmlString = htmlString.replaceAll("<br>", System.getProperty("line.separator") + "<br>"); // do replacements for all tags that should result in line-breaks

Document.OutputSettings settings = new OutputSettings();
settings.prettyPrint(false); // to keep line-breaks

String cleanedSource = Jsoup.clean(htmlString, "", Whitelist.none(), settings);

System.out.println(cleanedSource);

输出

 Hi



 Data is written in this mail.
[... four more empty lines]