XStream avoid collection xml element
-
20-09-2019 - |
Question
Given a List
of POJO's, if I serialize them with XStream I get:
<list>
<pojo>
<a>a</a>
<b>b</b>
</pojo>
<pojo>
<a>a</a>
<b>b</b>
</pojo>
</list>
How can I do the serialization and omit the <list> </list>
entries? I've used addImplicitCollection
for a similar purpose but that was to omit the collection instance variable name when the collection was a member of a class being serialized.
Note: This question appears similar but not exactly relevant (I think).
Solution
You can't. Imagine that <list>
node was gone - how would XStream know how to deserialize this XML? It can be list / set / array / something else entirely. Furthermore, imagine you have an object containing a list of your pojo
followed by a single pojo
field - they'd be jumbled together.
That said, if you have no intention of deserializing this, you can implement your own stream driver and writer akin to JSON writer that would drop the <list>
for you.
OTHER TIPS
These days (using XStream 1.4.1) it is possible to omit the container element from the output using "implicit collections"
XML must have a single root element, so ChssPly76 is right, but of course if you are streaming XML then you can just write each pojo one after the other (make sense from a memory perspective as well).
See http://x-stream.github.io/objectstream.html for details.