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

标签 java html jsoup jakarta-mail

我尝试实现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它,当你 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]

关于java - 如何删除这些 html 元素,同时保留格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40232246/

相关文章:

asp.net - 构建时验证所有 ASPX、ASCX 和 HTML 文件

java - 剪切 jsoup 接收到的字符串

java - "Screen scrape"与具有 ID 的元素的 Jsoup

java - Spring MVC 与 Hibernate; getCurrentSession() 时嵌套异常为 java.lang.NullPointerException

java - 返回java中的子类类型

java - Maven 部署文件目标 : Why does the first execution interfere with the second one?

java - JSoup 触发器 "java.nio.charset.IllegalCharsetNameException: iso-8859-1"

java - 在 Java 中,使用 JPA2,我应该使用哪个类来保存日期信息?

html - CSS DIV 奇怪的行为

javascript - 获取元素相对于父div Jquery的xy位置