Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple XML parse XML to List

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?

like image 774
YETI Avatar asked Jul 03 '12 03:07

YETI


People also ask

How do I parse an XML text file into an array?

Step 1: Creating an XML file (Optional): Create an XML file which need to convert into the array. <? xml version = '1.0' ?> Step 2: Convert the file into string: XML file will import into PHP using file_get_contents() function which read the entire file as a string and store into a variable.

Can you parse XML?

The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML. However, before an XML document can be accessed, it must be loaded into an XML DOM object. All modern browsers have a built-in XML parser that can convert text into an XML DOM object.

What are the two methods of parsing in XML document?

To read and update, create and manipulate an XML document, you will need an XML parser. In PHP there are two major types of XML parsers: Tree-Based Parsers. Event-Based Parsers.


1 Answers

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
like image 63
ollo Avatar answered Nov 04 '22 01:11

ollo