When creating a REST/XML webservice, and showing List
objects: should the list elements be wrapped in a list element (eg <persons>
), or should the response just list multiple <person>
elements?
Example:
@XmlElement
private List<Person> persons;
public class Person {
private String name;
private int age;
//...
}
Nested:
<rsp>
<persons>
<person>
<name />
<age />
</person>
<person>
...
</person>
</persons>
</rsp>
Flat:
<rsp>
<person>
<name />
<age />
</person>
<person>
...
</person>
</rsp>
XML Array has defined as a variable array grouping together the same items in the list and contains one or more child items. Arrays being a sequence of elements declared with the same name. A multi-dimensional Array is created for a collection of elements. The arrays are done by creating functions by pairs.
XML provides the capability to display data because it is a markup language. JSON supports array. XML doesn't support array.
The XML object model is a collection of objects that you use to access and manipulate the data stored in an XML document. The XML document is modeled after a tree, in which each element in the tree is considered a node. Objects with various properties and methods represent the tree and its nodes.
It'll be apt to wrap the list in a parent element like persons
. Two reasons for doing that:
As pointed out by @tanyehzheng, it allows adding attributes to the list like size.
With a wrapped style, it allows your response object <rsp>
to be extensible to include other objects, in a cleaner fashion. Say tomorrow we wish to add data like below (this is just an example)
<rsp>
<persons>
<person>
<name />
<age />
</person>
<person>
...
</person>
</persons>
<performanceInfo>
<processingTime>122</processingTime>
</performanceInfo>
</rsp>
I would have wrapped it nested. Because it's more natural to add metadata like the size of the list
<persons size="42">
<person>
...
</person>
<person>
...
</person>
.
.
.
<persons>
When it comes right down to it, I would go through a few well known RESTFUL interfaces ( or at least interfaces used in your services environment ). I would try to be as consistent as possible so your ecosystem of developers will have an intuitive start to understanding the API that you have designed.
From a technical perspective, I suspect that the wrapping of the element can make parsing or application coding more efficient. Of course, there are the benefits of being able to provide attributes for the list itself (as tanyehzheng has already stated ).
Personally, I prefer the wrapped XML as well, but not for any technical reasons. In XML editors/viewers, the element can be collapsed and thus the response can be made more terse for humans.
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