Java – simple XML parsing from XML to list
•
Java
I use simple XML (simple-xml-2.6.2. Jar) to parse XML files, such as:
<?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 want to be ArrayList. How?
Solution
This is a possible solution and I hope it can help you:
Comments 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
}
Sample class with list:
@Root(name="elementList")
public class Example
{
@ElementList(required=true,inline=true)
private List<Order> list = new ArrayList<>();
// ...
}
Here are some code for reading the code:
Serializer ser = new Persister(); Example example = ser.read(Example.class,file); // file = your xml file // 'list' Now contains all your Orders
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
