Question

I want to create an inline list in XML. Something like this:

<numbers>
<phone>1234</phone>
<phone>5678</phone>
<phone>3456</phone>
</numbers>

The tutorial here highlights how it can be done.

Now, I have no idea about how to deal with

public Order(@Attribute(name="name") String name, 
             @Element(name="product") String product)  

or

public OrderManager(@ElementList(name="orders") List<Order> orders) {
        this.orders = orders;
    }

I have never worked with lists in Java.

My case: A database, upon querying, will fill up an array phone_numbers[x]. How am I supposed to generate the XML file like above using the values in the array and Constructor Injection?

Was it helpful?

Solution

Suppose you had a class PhoneNumbers like so:

@Root
public class PhoneNumbers {
    @ElementArray(name="numbers", entry = "phone")
    private String[] phones;

    public PhoneNumbers(String[] phones) {
        this.phones = phones;
    }
}

There is no need in this case to convert to a List.

String[] phone_numbers= new String[] { "1234", "5678" }; // populate from DB instead
PhoneNumbers numbers = new PhoneNumbers(phone_numbers);

// to serialize
Serializer serializer = new Persister();
serializer.write(numbers, System.out);

This will print out the following XML:

<phoneNumbers>
   <numbers length="2">
      <phone>1234</phone>
      <phone>5678</phone>
   </numbers>
</phoneNumbers>

There is no way for the Simple framework to NOT print a root element. So you could String strip the root element if you absolutely need to just serialize the numbers element.

That's it!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top