Search code examples
javaxml-serializationxstream

xstream attribute interdependencies


I am pretty new to xstream. Consider a piece of xml:

<?xml version="1.0"?>
<els>
    <el attInt="3" attDbl="1.34525"/>
</els>

I need to convert the attDbl attribute shifting the decimal point by the number of places specified by attInt. I dont see how to do it using a convertor as I dont seem to have access to both attributes within the convertor interface. Is this something I can do with a converter or should I be using xslt for this purpose?

Thanks for your help


Solution

  • A converter acting at the 'el' level does have access to both attributes via the reader argument:

    public class ElConverter implements Converter {
    
        @Override
        public Object unmarshall(HierarchicalStreamReader reader, UnmarshallingContext context) {
            int attInt = Integer.parseInt(reader.getAttribute("attInt"));
            double attDbl = Double.parseDouble(reader.getAttribute("attDbl"));
    
            ...
        }
    
        @Override
        public boolean canConvert(Class type) {
            return El.class.isAssignableFrom(type);
        }