Using Aliases to refactor XML

Posted by andy in : Agile,Refactoring,Software on February 23, 2004. There is 1 response »

I have been playing with XStream for converting java classes into xml.

We can convert a class such as this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package xtream.demo;
 
import java.util.Date;
 
public class NotVeryUsefulBean {
    public String someString;
    public Date someDate;
    public int someInt;
 
    public NotVeryUsefulBean(String someString, Date someDate, int someInt) {
        this.someString = someString;
        this.someDate = someDate;
        this.someInt = someInt;
    }
}

into xml that looks like this.

1
2
3
4
5
<xtream .demo.NotVeryUsefulBean>
  <somestring>Sample String</somestring>
  <somedate>2006-07-22 14:45:02.117 PM</somedate>
  <someint>999</someint>
</xtream>

The xml is nice and clean. Like most implementations, XStream embeds the name of the class in the xml. This can cause problems when you rename a class, or move it to a different package. The xml could be on a customers’ machine, well away from my refactoring IDE. I have been bitten by this lately.

Then I realised that XStream has aliases. Joe added aliases to make it easier to read the xml. You map an alias to a class. Here is an example of using a “MyAlias” for the “NotVeryUsefulBean” class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import com.thoughtworks.xstream.XStream;
import xtream.demo.NotVeryUsefulBean;
 
import java.util.Date;
 
public class XstreamDemoUsingAnAlias{
    public static void main(String[] args) {
        XStream xStream = new XStream();
        xStream.alias("MyAlias", NotVeryUsefulBean.class);
 
        NotVeryUsefulBean bean = new NotVeryUsefulBean("String", new Date(), 999);
 
        String xml = xStream.toXML(bean);
        System.out.println("xml = " + xml);
    }
}

And the xml now looks like this

1
2
3
4
5
<myalias>
  <somestring>String</somestring>
  <somedate>2006-07-22 15:02:37.996 PM</somedate>
  <someint>999</someint>
</myalias>

Not a class name in sight. When I rename classes and move them into different packages, the refactoring tool will update the alias without breaking the xml. Nice!

One response

  1. Arnaud
    June 15th, 2011 | Permalink

    Thanks a lot, typed “refactoring xstream” in google and found exactly a solution to my problem !
    Cheers

Trackbacks

Leave a Reply

 

Site Map | design by twothirty