例如,我有两个用户帐户:发件人和收件人。他们每个人都有自己的登录名和密码。这些字段保存在xml配置文件中,如下所示:
<SenderData>
<login>awesomeLogin</login>
<password>awesomePass</password>
</SenderData>
在我的测试中,我创建了Account类,我想在那里放置发件人或收件人数据:
@XStreamAlias("SenderData")
public class Account {
private String login, password;
}
我使用com.thoughtworks.xstream @XStream
及其别名从xml加载所需数据,使用@XStreamAlias("SenderData")
注释对类进行注释。
它适用于一个特定的xml源文件,但如果我有几个xml源(此处是发件人和收件人),如何使用@XStream加载适当的数据? 为了清楚起见,我的目标是拥有一个Account类的两个对象,如下所示:
Account sender = myXstream.load("SenderData", Account.class); //works!
Account recipient = myXstream.load("RecipientData", Account.class);//doesn't work
- 最后一个不起作用,因为我只能将一个@XStreamAlias("SenderData")
注释添加到Account类
答案 0 :(得分:1)
假设您必须加载XML并使用xstream-distribution-1.4.9
1.first xml(recipient.xml)
<RecipientData>
<login>naLogin</login>
<password>anaPass</password>
</RecipientData>
2。第二个XML(sender.xml)
<SenderData>
<login>awesomeLogin</login>
<password>awesomePass</password>
</SenderData>
使用此帐户类:
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("SenderData")
public class Account {
private String login, password;
public String getLogin() {
return login;
}
/*public void setLogin(String login) {
this.login = login;
}*/
public String getPassword() {
return password;
}
/*public void setPassword(String password) {
this.password = password;
}*/
public void toPtring(){
System.out.println("login="+this.getLogin());
System.out.println("pass="+this.getPassword());
}
}
和测试类:
public class maintest {
public static void main(String args[]) throws FileNotFoundException{
XStream xstream = new XStream();
xstream.alias("SenderData", Account.class);
FileReader r = new FileReader("sender.xml");
Account sender=(Account)xstream.fromXML(r);
sender.toPtring();
xstream.alias("RecipientData", Account.class);
FileReader r2 = new FileReader("recipient.xml");
Account recipient=(Account)xstream.fromXML(r2);
recipient.toPtring();
}
}
它的作品。喜欢这个结果
login=awesomeLogin
pass=awesomePass
login=naLogin
pass=anaPass
看看你的代码,看看你是否忘记了什么