使用xstream使用重复条目反序列化xml

时间:2011-09-20 20:10:55

标签: java xstream

我正在尝试读取xml文件并将其内容存储为对象供以后使用。我可以使用toXML()方法重现类似的对象并提供样本数据,但是当我在同一个对象上调用fromXML()时,我得到一个错误。问题是我有多个fiels实例。 xml看起来像这样......

<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>

所以在这个例子中有两个居民,每个人都有两个职称。我尝试将这些标记定义为构造函数中的arraylists,用于各自的类,但这似乎不起作用。如果我只有一个Resident或Title等实例,这样可以正常工作。

这是Java代码(从下面的评论中复制):

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;
}

}

1 个答案:

答案 0 :(得分:3)

以下是使用注释的方法。

@XStreamAlias("house")
public class House{

@XStreamAlias("Address")
private String address;

@XStreamImplicit
protected List<Resident> residents;

    ...

}

在Resident课程中,您可以:

@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

    ...

}

请记住处理注释。