views:

296

answers:

3

Hi.

We have an XML that needs to be converted to an object and vice versa. Something like Xstream does. Until now we were using Xstream to marshall and unmarshall the object/xml. However the problem is that an object that corresponds to XML in xstream, needs to have all the tags as attributes; else if XML contains any extra tags which are not present in object; it bombs.

Or, we need to have custom convertors written to make sure that the operation goes as desired. I was also suggested that common digester allows Xpath parsing from XML to an object.

I am wondering what is the best approach; as long as:

  1. I just want to convert XML to Object and vice versa.
  2. Have the ability to silently ignore any fields in XML that map not be present in mapping object.

What do you suggest?

A: 

I would suggest using http://simple.sourceforge.net/ I uses annotations to map attributes and elements and has a "non strict" mode which enables you to read from the XML document ignoring all attributes and elements not present in the Java object.

ng
Why use a proprietary solution like Simple, when you could use and industry standard like JAXB, http://bdoughan.blogspot.com/2010/07/jaxb-xml-binding-standard.html
Blaise Doughan
I think you misunderstand the word proprietary, Simple has a more liberal license (Apache). Also, you can do more with Simple than you can with JAXB. Finally its easier to use, faster, more light weight, and works on Andriod, GAE, and any Java 1.5+ VM.
ng
+1  A: 

You need to use a custom MapperWrapper as documented here http://pvoss.wordpress.com/2009/01/08/xstream/

XStream xstream = new XStream() {
  @Override
  protected MapperWrapper wrapMapper(MapperWrapper next) {
    return new MapperWrapper(next) {
      @Override
      public boolean shouldSerializeMember(Class definedIn,
              String fieldName) {
        if (definedIn == Object.class) {
          return false;
        }
        return super.shouldSerializeMember(definedIn, fieldName);
      }
    };
  }
};

The only thing it does is tell XStream to ignore all fields that it does not know to deal with.

Christopher Oezbek
Or you could use JAXB that gives the desired behavior by default.
Blaise Doughan