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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With