Search code examples
javacollectionsxstream

XStream avoid collection xml element


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.