Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

java - How to convert List of Object to XML doc using XStream

How to convert List of Object to XML doc using XStream ?

and how to deserialize it back ?

This is my xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
</persons>

Person bean contains 3 fields how to convert back it to Bean List using custom converters ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't necessarily need a CustomConverter.

You need a class to hold your list:

public class PersonList {

    private List<Person> list;

    public PersonList(){
        list = new ArrayList<Person>();
    }

    public void add(Person p){
        list.add(p);
    }
}

To serialise the list to XML:

    XStream xstream = new XStream();
    xstream.alias("person", Person.class);
    xstream.alias("persons", PersonList.class);
    xstream.addImplicitCollection(PersonList.class, "list");

    PersonList list = new PersonList();
    list.add(new Person("ABC",12,"address"));
    list.add(new Person("XYZ",20,"address2"));

    String xml = xstream.toXML(list);

To deserialise xml to a list of person objects:

    String xml = "<persons><person>...</person></persons>";
    PersonList pList = (PersonList)xstream.fromXML(xml);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...