0

我有一个应用程序,它会输出一个包含电子邮件内容的 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"用于隐式收集

4

1 回答 1

1

该行:

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

是说类上有一个集合字段,To它是应该添加to实例的地方。Recipient

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

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

请参阅 JavaDocxstream.addImplicitCollection(Class, String, Class)

于 2013-01-21T13:05:01.453 回答