Simple XML parse XML to List

YETI picture YETI · Jul 3, 2012 · Viewed 8.4k times · Source

I use Simple XML (simple-xml-2.6.2.jar) to parse xml file like:

<?xml version="1.0" encoding="UTF-8" ?> 
<orderList> 
    <order id="1"> 
        <name>NAME1</name> 
    </order> 
    <order id="2"> 
        <name>NAME2</name> 
    </order> 
</orderList> 

The root Element contains subElements. I wanna it be ArrayList, How to do it?

Answer

ollo picture ollo · Aug 29, 2012

Here's a possible solution, hope it helps you:

Annotations of Order class:

@Root(name="order")
public class Order
{
    @Attribute(name="id", required=true)
    private int id;
    @Element(name="name", required=true)
    private String name;


    public Order(int id, String name)
    {
        this.id = id;
        this.name = name;
    }


    public Order() { }


    // Getter / Setter
}

Example class, containing the list:

@Root(name="elementList")
public class Example
{
    @ElementList(required=true, inline=true)
    private List<Order> list = new ArrayList<>();

    // ...
}

And here's some code for reading your code:

Serializer ser = new Persister();
Example example = ser.read(Example.class, file); // file = your xml file
// 'list' now contains all your Orders