如何在Java中反序列化xml文件中的电子邮件列表?

时间:2013-01-21 12:07:55

标签: java xml email xstream

我有一个应用程序将使用电子邮件的内容吐出XML文件。此XML文件将由其他应用程序解析,并将传递电子邮件。应用程序发送电子邮件的部分已经过验证。

实际发送电子邮件的方法是:

public void sendEmail(List<String> toRecipients, List<String> ccRecipients, List<String> bccRecipients, String subject, String body) { 

// code.. 

}

我尝试发送的测试电子邮件应来自此XML文件:

<?xml version="1.0" encoding="utf-8"?>
<email>
  <to>
    <recipient>user1@somecompany.com</recipient>
    <recipient>user2@somecompany.com</recipient>
  </to>
  <cc>
    <recipient>user3@somecompany.com</recipient>
  </cc>
  <bcc>
    <recipient>user5@somecompany.com</recipient>
  </bcc>
  <subject>test ABC </subject>
  <body><h1>test XYZ</h1></body>
</email>

我正在使用XStream库,我的问题在于解析列表。我尝试了几种不同的方法,但我被卡住了。 XML解析方法是:

private void parseXmlFile(String xmlFilePath) {
        XStream xstream = new XStream(new DomDriver());

        xstream.alias("email", EmailPojo.class);
        xstream.alias("recipient", Recipient.class);
        xstream.alias("to", To.class);
        xstream.alias("cc", Cc.class);
        xstream.alias("bcc", Bcc.class);

        xstream.addImplicitCollection(To.class, "to", "to", Recipient.class);
        // xstream.addImplicitCollection(To.class, "to");
        // xstream.addImplicitCollection(Cc.class, "cc");
        // xstream.addImplicitCollection(Bcc.class, "bcc");

        EmailPojo emailPojo = new EmailPojo();

        StringBuilder sb = new StringBuilder();
        try {
            // filename is filepath string
            BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilePath)));
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line.trim());
            }
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        List<EmailPojo> emailPojoList = new ArrayList<EmailPojo>();

        try {
            emailPojoList = (List<EmailPojo>) xstream.fromXML(sb.toString());

        } catch (Exception e) {
            emailPojo = null;// TODO: handle exception
        }
    }

这似乎很直接,但我无法做到这一点。 我在这儿失踪了吗?这有什么不对?

提前致谢!

编辑:忘记了异常输出:

Exception in thread "main" com.thoughtworks.xstream.InitializationException: No field "to"用于隐式集合

1 个答案:

答案 0 :(得分:1)

该行:

xstream.addImplicitCollection(To.class, "to", "to", Recipient.class);

To班上有一个名为to的收集字段,应该添加Recipient的实例。

没有看到To类,这是一个猜测,但我认为类To上的集合字段上的字段更可能被称为recipients,应注册:

xstream.addImplicitCollection(To.class, "recipients", Recipient.class);

请参阅JavaDoc以了解xstream.addImplicitCollection(Class, String, Class)