[英]how to deserialize a list of emails on a xml file in Java?
我有一個應用程序,該應用程序將吐出帶有電子郵件內容的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"
隱式集合Exception in thread "main" com.thoughtworks.xstream.InitializationException: No field "to"
該行:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.