Convert XML file to class variable?



I was messing around on XStream to get used using it. I can convert my Person variable to XML to give me this



<list>
<Person>
<name>Mitch</name>
<age>17</age>
<adress>Yehaaa</adress>
<fav-hobbie>Programming</fav-hobbie>
</Person>
<Person>
<name>Ant</name>
<age>18</age>
<adress>Mitch&apos;s House</adress>
<fav-hobbie>Football</fav-hobbie>
</Person>
</list>


I was wondering how I could read an XML file and create a new person variable with the name, adress, age and hobbie from the xml file?


Here is the code I have



public class base {

static XStream xstream = new XStream(new DomDriver());
static NewPerson person1 = new NewPerson();
static NewPerson person2 = new NewPerson();

static List<NewPerson> persons = new ArrayList();


public base(){

}

public static void main(String[] args) throws FileNotFoundException{
persons.add(person1);
persons.add(person2);
person1.name = "Mitch";
person1.adress = "52 Hope Street";
person1.age = 17;
person1.hobbie = "Programming";
person2.name = "Ant";
person2.adress = "Mitch's House";
person2.age = 18;
person2.hobbie = "Football";

String str = "res/file.xml";

xstream.processAnnotations(NewPerson.class);
xstream.toXML(persons, System.out);

}
}

@XStreamAlias("Person")
class NewPerson {

@XStreamAlias("name")
String name;

@XStreamAlias("age")
int age;

@XStreamAlias("adress")
String adress;

@XStreamAlias("fav-hobbie")
String hobbie;
}


Could anyone offer any example code to demonstrate how I would create a new Person variable from the XML file


No comments:

Post a Comment