0

我有这段代码可以实现ParserCallback并将HTML电子邮件转换为Plain文本。当我像这样解析电子邮件正文时,此代码工作正常=

  "DO NOT REPLY TO THIS EMAIL MESSAGE.   <br>---------------------------------------<br>\n" +
                "nix<br>---------------------------------------<br> Esfghjdfkj\n" +
                "</blockquote></div><br><br clear=\"all\"><div><br></div>-- <br><div dir=\"ltr\"><b>Regards <br>Nisj<br>Software Engineer<br></b><div><b>Bingo</b></div></div>\n" +
                "</div>"

但是当我解析这种电子邮件正文时,它返回 null,

 email = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html charset=us-ascii\"></head><body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\">Got it...so pls send to customer now.<div><br><div style=\"\"><div>On Nov 8, 2013, at 12:31 PM, <a href=\"mailto:xxxxxxx.com\">xxxxxxx.com</a> wrote:</div><br class=\"Apple-interchange-newline\"><blockquote type=\"cite\">Forwarding test.<br>---------------------------------------<br> ABCD.</blockquote></div><br></div></body></html>";

代码 :

import java.io.IOException;
import java.io.StringReader;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.Parser;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

public class EmailBody {
    public static void main(String[] args) throws IOException
    {
        String email = "";

        class EmailCallback extends ParserCallback
        {
            private String body_;
            private boolean divStarted_;

            public String getBody()
            {
                return body_;
            }

            @Override
            public void handleStartTag(Tag t, MutableAttributeSet a, int pos)
            {
                if (t.equals(Tag.DIV) && "ltr".equals(a.getAttribute(Attribute.DIR)))
                {
                    divStarted_ = true;
                }
            }

            @Override
            public void handleEndTag(Tag t, int pos)
            {
                if (t.equals(Tag.DIV))
                {
                    divStarted_ = false;
                }
            }

            @Override
            public void handleText(char[] data, int pos)
            {
                if (divStarted_)
                {
                    body_ = new String(data);
                }
            }
        }
        EmailCallback callback = new EmailCallback();
        Parser parser = new ParserDelegator();
        StringReader reader = new StringReader(email);
        parser.parse(reader, callback, true);
        reader.close();
        System.out.println(callback.getBody());
    }
}

你能说出原因吗,为什么会这样?

4

1 回答 1

1

您的代码只会从具有值属性的DIV元素中获取元素文本。该方法仅在标志为真时处理元素文本,仅当将此标志设置为真时才会发生这种情况。 在第一个电子邮件示例中,您有这样的元素,而在第二个电子邮件示例中,您没有这些元素。dirltrhandleTextdivStarted_handleStartTag

于 2013-11-11T09:26:17.577 回答