Search code examples
javaxmlxstream

XStream several node types in signle collection


I'm trying to deserialize such XML document:

<rootelem>
    <elementType1 arg1="..." />
    <elementType1 arg1="..." />
    <elementType1 arg1="..." />
    <elementType2 argA="..." argB="..." />
    <elementType2 argA="..." argB="..." />
    <elementType2 argA="..." argB="..." />
</rootelem>

By default XStream can parse only such form:

<rootelem>
    <list1>
        <elementType1 arg1="..." />
        <elementType1 arg1="..." />
        <elementType1 arg1="..." />
    </list1>

    <list2>
        <elementType2 argA="..." argB="..." />
        <elementType2 argA="..." argB="..." />
        <elementType2 argA="..." argB="..." />
    </list>
</rootelem>

This is because XStream use next format for collections:

<collection>
    <elem .... />
    <elem .... />
    <elem .... />
</collection>

and frame tags are obligatory. Collection can contain only single type nodes. So how can I parse such XML document? Now I've written my own convertor for this but I wonder are there some other ways?


Solution

  • I think that Implicit Collections is the solution for you.

    http://x-stream.github.io/alias-tutorial.html#implicit

    Here is the sample code:

    package com.thoughtworks.xstream;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
    
        public static void main(String[] args) {
    
                Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
                teamBlog.add(new Entry("first","My first blog entry."));
                teamBlog.add(new Entry("tutorial",
                        "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));
    
                XStream xstream = new XStream();
                xstream.alias("blog", Blog.class);
                xstream.alias("entry", Entry.class);
    
                xstream.addImplicitCollection(Blog.class, "entries");
    
                System.out.println(xstream.toXML(teamBlog));
        }
    }
    

    And the result:

    <blog>
      <author>
         <name>Guilherme Silveira</name>
      </author>
      <entry>
         <title>first</title>
         <description>My first blog entry.</description>
      </entry>
      <entry>
         <title>tutorial</title>
         <description>
              Today we have developed a nice alias tutorial. Tell your friends! NOW!
         </description>
      </entry>
    </blog>