问题
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>
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.
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;
}
}
回答1:
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
...
}
Remember to process the annotations.
来源:https://stackoverflow.com/questions/7491195/deserializing-xml-with-duplicate-entries-using-xstream