## The problem

Suppose that our client has defined a base XML file that we should make XStream read/write:

    <blog author="Guilherme Silveira">
      <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>

Based on the XML file above we shall create some model classes and configure XStream to write/read from this format.

## The model

First things first, the classes which shall represent our xml files are shown next, beginning with a simple Blog:

    package com.thoughtworks.xstream;

    public class Blog {
            private Author writer;
            private List entries = new ArrayList();

            public Blog(Author writer) {
                    this.writer = writer;
            }

            public void add(Entry entry) {
                    entries.add(entry);
            }

            public List getContent() {
                    return entries;
            }
    }

A basic author with name:

    package com.thoughtworks.xstream;

    public class Author {
            private String name;
            public Author(String name) {
                    this.name = name;
            }
            public String getName() {
                    return name;
            }
    }

A blog entry contains a title and description:

    package com.thoughtworks.xstream;

    public class Entry {
            private String title, description;
            public Entry(String title, String description) {
                    this.title = title;
                    this.description = description;
            }
    }

Although we did not create many getters/setters its up to you to create those you wish or those which make sense.

## A simple test

We can easily instantiate a new blog and use it with xstream:

    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();
            System.out.println(xstream.toXML(teamBlog));

    }

And the resulting XML is not so nice as we would want it to be:

    <com.thoughtworks.xstream.Blog>
      <writer>
        <name>Guilherme Silveira</name>
      </writer>
      <entries>
        <com.thoughtworks.xstream.Entry>
          <title>first</title>
          <description>My first blog entry.</description>
        </com.thoughtworks.xstream.Entry>
        <com.thoughtworks.xstream.Entry>
          <title>tutorial</title>
          <description>
            Today we have developed a nice alias tutorial. Tell your friends! NOW!
          </description>
        </com.thoughtworks.xstream.Entry>
      </entries>
    </com.thoughtworks.xstream.Blog>

## Class aliasing

The first thing we shall change is how XStream refers to the com.thoughtworks.xstream.Blog class. We shall name it simply blog: let's create an alias called blog to the desired class:

    xstream.alias("blog", Blog.class);

Using the same idea, we can alias the 'Entry' class to 'entry':

    xstream.alias("entry", Entry.class);

The result now becomes:

    <blog>
      <writer>
        <name>Guilherme Silveira</name>
      </writer>
      <entries>
        <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>
      </entries>
    </blog>

## Field aliasing

Next we will change the name of the writer tag, but this time we have to use a field alias:

    xstream.aliasField("author", Blog.class, "writer");

The result now becomes:

    <blog>
      <author>
        <name>Guilherme Silveira</name>
      </author>
      <entries>
        <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>
      </entries>
    </blog>

## Omit the 'entries' tag

Now let's implement what was called an implicit collection: whenever you have a collection which doesn't need to display it's root tag, you can map it as an implicit collection.

In our example, we do not want to display the entries tag, but simply show the entry tags one after another.

A simple call to the addImplicitCollection method shall configure XStream and let it know that we do not want to write the entries tag as described above:

    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));

            }
    }

Pay attention to the addImplicitCollection method call: it describes which class and which member variable shall assume the behaviour we described.

The result is almost what we wanted:

    <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>

## Attribute aliasing

The next step is to set the writer member variable as an XML attribute. In order to do this, we shall tell XStream to alias the writer field of the Blog class as an "author" attribute:

                    xstream.useAttributeFor(Blog.class, "writer");
                    xstream.aliasField("author", Blog.class, "writer");

And now it leaves us with one problem: how does XStream converts an Author in a String so it can be written as a XML tag attribute?

Attributes cannot be written for types that are handled by Converter implementations, we have to use a SingleValueConverter and implement our own converter for the Author:

    class AuthorConverter implements SingleValueConverter {
    }

The first method to implement tells XStream which types it can deal with:

            public boolean canConvert(Class type) {
                    return type.equals(Author.class);
            }

The second one is used to extract a String from an Author:

            public String toString(Object obj) {
                    return ((Author) obj).getName();
            }

And the third one does the opposite job: takes a String and returns an Author:

            public Object fromString(String name) {
                    return new Author(name);
            }

Finally, the entire single value converter, responsible for converting Strings to Objects (Authors in this case) is:

    class AuthorConverter implements SingleValueConverter {

            public String toString(Object obj) {
                    return ((Author) obj).getName();
            }

            public Object fromString(String name) {
                    return new Author(name);
            }

            public boolean canConvert(Class type) {
                    return type.equals(Author.class);
            }

    }

And let's register this converter:

    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");

                    xstream.useAttributeFor(Blog.class, "author");
                    xstream.registerConverter(new AuthorConverter());

                    System.out.println(xstream.toXML(teamBlog));

            }
    }

The result?

    <blog author="Guilherme Silveira">
      <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>

You have to be aware, that attribute values normally have to be normalized by the XML parser as required by the W3C spec. Leading and trailing whitespaces are normally removed as well as sequential ones! Therefore a deserialized string might differ from the value visible in the XML representation.

## Package aliasing

In the example above we have so far always used class aliases for the Blog and Entry type. Sometimes it is necessary to map existing class types to others simply by changing the package name. Let us go back to the first attempt of our tutorial, but this time we alias the package name instead of the individual classes:

    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.aliasPackage("my.company", "org.thoughtworks");
            System.out.println(xstream.toXML(teamBlog));

    }

And the resulting XML contains now the classes with the aliased package names:

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

Please recognize that the package name alias works also for sub packages in this example.

## Summing up

To recap:

- You can use class aliases to change tag names
- You can use field aliases to change tag names
- You can use package aliases to change tag names
- Fields can be written as attributes if the field type is handled by a SingleValueConverter

Don't forget to read the converter tutorial to see other type of converters that you can create using XStream.