将XML文件转换为类变量?

时间:2015-02-11 06:16:48

标签: java xml xstream

我正在乱用XStream来使用它。我可以将我的Person变量转换为XML来给我这个

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

我想知道如何读取XML文件并使用xml文件中的名称,地址,年龄和爱好创建一个新的person变量?

这是我的代码

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

是否有人可以提供任何示例代码来演示如何从xml文件

创建新的Person变量

2 个答案:

答案 0 :(得分:0)

从他们的教程中,

String xml = xstream.toXML(persons);
List<Person> personList= (List<Person>)xstream.fromXML(xml);

答案 1 :(得分:0)

你也可以这样做:

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
    }