-1

I am 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 am wondering how I could read an XML file and create a new person variable with the name, address, age and hobby 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

Indrajeet
  • 5,490
  • 2
  • 28
  • 43

2 Answers2

0

From their tutorial,

String xml = xstream.toXML(persons);
List<Person> personList= (List<Person>)xstream.fromXML(xml);
Evan Knowles
  • 7,426
  • 2
  • 37
  • 71
0

You can also do like this:

public class Test{
    public static void main(String args[]){
    FileReader xmlReader = new FileReader("filePerson.xml");//File.xml will containe the xml content which you want to parse
    XStream stream = new XStream(new StaxDriver());
    stream.alias("Person",Person.class);

    ArrayList<Person> person = (ArrayList<Person>) stream.fromXML(xmlReader);
    //If you want to retrieve then you can use iterator or foreach loop
    for(Person P: person){
     //        Write your logic
    }
Samraan
  • 204
  • 1
  • 2
  • 14