使用 xstream 反序列化具有重复条目的 xml [英] Deserializing xml with duplicate entries using xstream
问题描述
我试图读入一个 xml 文件并将其内容存储为一个对象以供以后使用.我可以使用 toXML() 方法重现一个类似的对象并提供示例数据,但是当我在同一个对象上调用 fromXML() 时,我得到一个错误.问题是我有多个字段实例.xml 看起来像这样...
I am trying to read in an xml file and store its contents as an object for later use. I can reproduce a similar object using the toXML() method and providing sample data however when I call fromXML() on the same object I get an error. The problem is I have multiple instances of fiels. The xml looks something like this...
<House>
<Address>
<Number>1234</Number>
<Street>Sample St.</Street>
<City>Sample City</City>
</Address>
<Resident>
<Name>Joe</Name>
<Age>38</Age>
<Profession>
<Title>Engineer</Title>
<Title>Developer</Title>
</Profession>
</Resident>
<Resident>
<Name>Cathy</Name>
<Age>35</Age>
<Profession>
<Title>Engineer</Title>
<Title>Developer</Title>
</Profession>
</Resident>
</House>
所以在这个例子中,有两个居民,他们每个人都有两个职位.我尝试将这些标签定义为它们各自类的构造函数中的数组列表,但这似乎不起作用.如果我只有一个 Resident 或 Title 等实例,这很好用.
So in this example there are two residents and they each have two job titles. I tried defining these tags as arraylists in the constructors' for their respective classes but that didn't seem to work. This works fine if I only have one instance of Resident or Title etc.
这是Java代码(从下面的评论中复制):
Here is the Java code (copied from comment below):
XStream xstream = new XStream(new DomDriver());
FileReader fin = new FileReader("path_to_file.xml");
BufferedReader br = new BufferedReader(fin);
while(br.ready())
{
str += br.readLine() + "\n";
}
House house = (House)xstream.fromXML(str);
import java.util.ArrayList;
public class House {
private Address Address;
private ArrayList<Resident> Resident;
public House(Address address, ArrayList<Resident> resident) {
Address = address;
Resident = resident;
}
public Address getAddress() {
return Address;
}
public void setAddress(Address address) {
Address = address;
}
public ArrayList<Resident> getResident() {
return Resident;
}
public void setResident(ArrayList<Resident> resident) {
Resident = resident;
}
}
推荐答案
这里是使用注解的方法.
Here is how to do it using annotations.
@XStreamAlias("house")
public class House{
@XStreamAlias("Address")
private String address;
@XStreamImplicit
protected List<Resident> residents;
...
}
在常驻班上,您会这样做:
And at the Resident class you do:
@XStreamAlias("resident")
public class Resident{
@XStreamAlias("name")
private String name;
@XStreamAlias("age")
private int age;
@XStreamAlias("profession")
private String profession;
@XStreamImplicit
protected List<String> titles
...
}
记得处理注释.
这篇关于使用 xstream 反序列化具有重复条目的 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!