Codebase list libxstream-java / 0337d7d xstream-distribution / src / content / alias-tutorial.html
0337d7d

Tree @0337d7d (Download .tar.gz)

alias-tutorial.html @0337d7draw · history · blame

<html>
<!--
 Copyright (C) 2006 Joe Walnes.
 Copyright (C) 2006, 2007, 2008, 2011 XStream committers.
 All rights reserved.
 
 The software in this package is published under the terms of the BSD
 style license a copy of which has been included with this distribution in
 the LICENSE.txt file.
 
 Created on 24. March 2006 by Guilherme Silveira
 -->
  <head>
    <title>Alias Tutorial</title>
  </head>
  <body>
<h2 id="problem">The problem</h2>
<p>Suppose that our client has defined a base XML file that we should make XStream read/write:</p>
<div class="Source Java"><pre>&lt;blog author=&quot;Guilherme Silveira&quot;&gt;
  &lt;entry&gt;
    &lt;title&gt;first&lt;/title&gt;
    &lt;description&gt;My first blog entry.&lt;/description&gt;
  &lt;/entry&gt;
  &lt;entry&gt;
    &lt;title&gt;tutorial&lt;/title&gt;
    &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    &lt;/description&gt;
  &lt;/entry&gt;
&lt;/blog&gt;</pre>

<p>Based on the XML file above we shall create some model classes and configure XStream to write/read from this format.</p></div>
<div class="section">
<h2 id="model">The model</h2>
<p>First things first, the classes which shall represent our xml files are shown next, beginning with a simple Blog:</p>
<div class="Source Java"><pre>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;
        }
}</pre></div>
<p>A basic author with name:</p>
<div class="Source Java"><pre>package com.thoughtworks.xstream;

public class Author {
        private String name;
        public Author(String name) {
                this.name = name;
        }
        public String getName() {
                return name;
        }
}</pre></div>
<p>A blog entry contains a title and description:</p>
<div class="Source Java"><pre>package com.thoughtworks.xstream;

public class Entry {
        private String title, description;
        public Entry(String title, String description) {
                this.title = title;
                this.description = description;
        }
}</pre></div>
<p>Although we did not create many getters/setters its up to you to create those you wish or those which make sense.</p></div>
<div class="section">
<h2 id="test">A simple test</h2>
<p>We can easily instantiate a new blog and use it with xstream:</p>
<div class="Source Java"><pre>public static void main(String[] args) {

        Blog teamBlog = new Blog(new Author(&quot;Guilherme Silveira&quot;));
        teamBlog.add(new Entry(&quot;first&quot;,&quot;My first blog entry.&quot;));
        teamBlog.add(new Entry(&quot;tutorial&quot;,
                &quot;Today we have developed a nice alias tutorial. Tell your friends! NOW!&quot;));

        XStream xstream = new XStream();
        System.out.println(xstream.toXML(teamBlog));

}</pre></div>
<p>And the resulting XML is not so nice as we would want it to be:</p>
<div class="Source Java"><pre>&lt;com.thoughtworks.xstream.Blog&gt;
  &lt;writer&gt;
    &lt;name&gt;Guilherme Silveira&lt;/name&gt;
  &lt;/writer&gt;
  &lt;entries&gt;
    &lt;com.thoughtworks.xstream.Entry&gt;
      &lt;title&gt;first&lt;/title&gt;
      &lt;description&gt;My first blog entry.&lt;/description&gt;
    &lt;/com.thoughtworks.xstream.Entry&gt;
    &lt;com.thoughtworks.xstream.Entry&gt;
      &lt;title&gt;tutorial&lt;/title&gt;
      &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      &lt;/description&gt;
    &lt;/com.thoughtworks.xstream.Entry&gt;
  &lt;/entries&gt;
&lt;/com.thoughtworks.xstream.Blog&gt;</pre></div></div>
<div class="section">
<h2 id="class_aliasing">Class aliasing</h2>
<p>The first thing we shall change is how XStream refers to the <b>com.thoughtworks.xstream.Blog</b> class.
We shall name it simply <i>blog</i>: let's create an alias called <i>blog</i> to the desired class:</p>
<div class="Source Java"><pre>xstream.alias(&quot;blog&quot;, Blog.class);</pre></div>
<p>Using the same idea, we can alias the 'Entry' class to 'entry':</p>
<div class="Source Java"><pre>xstream.alias(&quot;entry&quot;, Entry.class);</pre></div>
<p>The result now becomes:</p>
<div class="Source Java"><pre>&lt;blog&gt;
  &lt;writer&gt;
    &lt;name&gt;Guilherme Silveira&lt;/name&gt;
  &lt;/writer&gt;
  &lt;entries&gt;
    &lt;entry&gt;
      &lt;title&gt;first&lt;/title&gt;
      &lt;description&gt;My first blog entry.&lt;/description&gt;
    &lt;/entry&gt;
    &lt;entry&gt;
      &lt;title&gt;tutorial&lt;/title&gt;
      &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      &lt;/description&gt;
    &lt;/entry&gt;
  &lt;/entries&gt;
&lt;/blog&gt;</pre></div></div>
<div class="section">
<h2 id="field_aliasing">Field aliasing</h2>
<p>Next we will change the name of the writer tag, but this time we have to use a field alias:</p>
<div class="Source Java"><pre>xstream.aliasField(&quot;author&quot;, Blog.class, &quot;writer&quot;);</pre></div>
<p>The result now becomes:</p>
<div class="Source Java"><pre>&lt;blog&gt;
  &lt;author&gt;
    &lt;name&gt;Guilherme Silveira&lt;/name&gt;
  &lt;/author&gt;
  &lt;entries&gt;
    &lt;entry&gt;
      &lt;title&gt;first&lt;/title&gt;
      &lt;description&gt;My first blog entry.&lt;/description&gt;
    &lt;/entry&gt;
    &lt;entry&gt;
      &lt;title&gt;tutorial&lt;/title&gt;
      &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      &lt;/description&gt;
    &lt;/entry&gt;
  &lt;/entries&gt;
&lt;/blog&gt;</pre></div></div>
<div class="section">
<h2 id="implicit">Implicit Collections</h2>
<p>Now let's implement what was called an <b>implicit collection</b>: whenever you have a collection which doesn't need
to display it's root tag, you can map it as an implicit collection.</p>
<p>In our example, we do not want to display the <b>entries</b> tag, but simply show the <b>entry</b> tags one after
another.</p>
<p>A simple call to the <b>addImplicitCollection</b> method shall configure XStream and let it know that we do not want to
write the <b>entries</b> tag as described above:</p>
<div class="Source Java"><pre>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(&quot;Guilherme Silveira&quot;));
                teamBlog.add(new Entry(&quot;first&quot;,&quot;My first blog entry.&quot;));
                teamBlog.add(new Entry(&quot;tutorial&quot;,
                        &quot;Today we have developed a nice alias tutorial. Tell your friends! NOW!&quot;));

                XStream xstream = new XStream();
                xstream.alias(&quot;blog&quot;, Blog.class);
                xstream.alias(&quot;entry&quot;, Entry.class);

                xstream.addImplicitCollection(Blog.class, &quot;entries&quot;);

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

        }
}</pre></div>
<p>Pay attention to the <b>addImplicitCollection</b> method call: it describes which class and which member variable
shall assume the behaviour we described.</p>
<p>The result is almost what we wanted:</p>
<div class="Source Java"><pre>&lt;blog&gt;
  &lt;author&gt;
    &lt;name&gt;Guilherme Silveira&lt;/name&gt;
  &lt;/author&gt;
  &lt;entry&gt;
    &lt;title&gt;first&lt;/title&gt;
    &lt;description&gt;My first blog entry.&lt;/description&gt;
  &lt;/entry&gt;
  &lt;entry&gt;
    &lt;title&gt;tutorial&lt;/title&gt;
    &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    &lt;/description&gt;
  &lt;/entry&gt;
&lt;/blog&gt;</pre></div></div>
<p>Just as a side note: An array or a map can also be declared as implicit.</p>
<div class="section">
<h2 id="attributes">Attribute aliasing</h2>
<p>The next step is to set the <b>writer</b> member variable as an XML attribute. In order to do this, we shall tell
XStream to alias the <b>writer</b> field of the <b>Blog</b> class as an "author" attribute:</p>
<div class="Source Java"><pre>                xstream.useAttributeFor(Blog.class, &quot;writer&quot;);
                xstream.aliasField(&quot;author&quot;, Blog.class, &quot;writer&quot;);</pre></div>
<p>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?</p>
<p>Attributes cannot be written for types that are handled by Converter implementations, we have to use a
<b>SingleValueConverter</b> and implement our own converter for the Author:</p>
<div class="Source Java"><pre>class AuthorConverter implements SingleValueConverter {
}</pre></div>
<p>The first method to implement tells XStream which types it can deal with:</p>
<div class="Source Java"><pre>        public boolean canConvert(Class type) {
                return type.equals(Author.class);
        }</pre></div>
<p>The second one is used to extract a String from an Author:</p>
<div class="Source Java"><pre>        public String toString(Object obj) {
                return ((Author) obj).getName();
        }</pre></div>
<p>And the third one does the opposite job: takes a String and returns an Author:</p>
<div class="Source Java"><pre>        public Object fromString(String name) {
                return new Author(name);
        }</pre></div>
<p>Finally, the entire single value converter, responsible for converting Strings to Objects (Authors in this case) is:</p>
<div class="Source Java"><pre>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);
        }

}</pre></div>
<p>And let's register this converter:</p>
<div class="Source Java"><pre>public class Test {

        public static void main(String[] args) {

                Blog teamBlog = new Blog(new Author(&quot;Guilherme Silveira&quot;));
                teamBlog.add(new Entry(&quot;first&quot;,&quot;My first blog entry.&quot;));
                teamBlog.add(new Entry(&quot;tutorial&quot;,
                        &quot;Today we have developed a nice alias tutorial. Tell your friends! NOW!&quot;));

                XStream xstream = new XStream();
                xstream.alias(&quot;blog&quot;, Blog.class);
                xstream.alias(&quot;entry&quot;, Entry.class);

                xstream.addImplicitCollection(Blog.class, &quot;entries&quot;);

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

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

        }
}</pre></div>
<p>The result?</p>
<div class="Source Java"><pre>&lt;blog author=&quot;Guilherme Silveira&quot;&gt;
  &lt;entry&gt;
    &lt;title&gt;first&lt;/title&gt;
    &lt;description&gt;My first blog entry.&lt;/description&gt;
  &lt;/entry&gt;
  &lt;entry&gt;
    &lt;title&gt;tutorial&lt;/title&gt;
    &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    &lt;/description&gt;
  &lt;/entry&gt;
&lt;/blog&gt;</pre></div>
</div>

<p class=highlight>You have to be aware, that attribute values normally have to be normalized by the XML parser as
required by the <a href="http://www.w3.org/TR/REC-xml/#AVNormalize">W3C spec</a>. 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.</p>

<div class="section">
<h2 id="packages">Package aliasing</h2>

<p>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:</p>
<div class="Source Java"><pre>public static void main(String[] args) {

        Blog teamBlog = new Blog(new Author(&quot;Guilherme Silveira&quot;));
        teamBlog.add(new Entry(&quot;first&quot;,&quot;My first blog entry.&quot;));
        teamBlog.add(new Entry(&quot;tutorial&quot;,
                &quot;Today we have developed a nice alias tutorial. Tell your friends! NOW!&quot;));

        XStream xstream = new XStream();
        xstream.aliasPackage("my.company", "org.thoughtworks");
        System.out.println(xstream.toXML(teamBlog));

}</pre></div>
<p>And the resulting XML contains now the classes with the aliased package names:</p>
<div class="Source Java"><pre>&lt;my.company.xstream.Blog&gt;
  &lt;author&gt;
    &lt;name&gt;Guilherme Silveira&lt;/name&gt;
  &lt;/author&gt;
  &lt;entries&gt;
    &lt;my.company.xstream.Entry&gt;
      &lt;title&gt;first&lt;/title&gt;
      &lt;description&gt;My first blog entry.&lt;/description&gt;
    &lt;/my.company.xstream.Entry&gt;
    &lt;my.company.xstream.Entry&gt;
      &lt;title&gt;tutorial&lt;/title&gt;
      &lt;description&gt;
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      &lt;/description&gt;
    &lt;/my.company.xstream.Entry&gt;
  &lt;/entries&gt;
&lt;/my.company.xstream.Blog&gt;</pre></div>
<p>Please recognize that the package name alias works also for sub packages in this example.</p>
</div>

<div class="section">
<h2 id="summary">Summing up</h2>
<p>To recap:</p>
<ul>
<li>You can use class aliases to change tag names</li>
<li>You can use field aliases to change tag names</li>
<li>You can use package aliases to change tag names</li>
<li>Fields can be written as attributes if the field type is handled by a SingleValueConverter</li>
</ul>
<p>Don't forget to read the <a href="converter-tutorial.html">converter tutorial</a> to see other type of converters that you can create using XStream.
Or look into the condensed overview how to configure XStream to <a href="manual-tweaking-output.html">tweak the output</a>.</p>
</div>

  </body>
</html>