Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xstream how to avoid a field with specific value while marshaling

Tags:

java

xml

xstream

I want to create an xml in the following format

<parm-list>
<param>
<NAME>somename</NAME>
<VALUE>somevalue</VALUE>
</param>
<param>
<NAME>somename</NAME>
<VALUE>somevalue</VALUE>
</param>
<param>
<NAME>somename</NAME>
<VALUE>somevalue</VALUE>
</param>
<param>
<NAME>somename</NAME>
<VALUE>somevalue</VALUE>
</param>
</param-list>

What can i do if i don't want a <PARAM> field with specific <NAME> in it?

like image 750
Hrishi Avatar asked Nov 13 '22 22:11

Hrishi


1 Answers

Although I really don't think that Xstream is really appropriate for the task, it does seem to be possible.

You could implement your own converter similar to one of those. If you take a look at Converter interface, you'll see that you can easily skip an element by not writing anything to HierarchicalStreamWriter.

public class ParamConverter implements Converter{

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

    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context){
        Param param = (Param)source;
        if (NAME_TO_SKIP.equals(param.getName()){
            return;
        }
        // delegate to ReflectionConverter or something else appropriate.
    }   
}

To register converter simply call xStram.registerConverter(new ParamConverter());.

For more information please read this tutorial on converters.

like image 105
Ivan Koblik Avatar answered Nov 15 '22 10:11

Ivan Koblik