Dynamically assign attribute name in SimpleXML (java)

I have the following class:

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;

@Root(name="PickLineXtra")
public class PickXtra {
    private final String key;   
    @Attribute(name=this.key)
    private String value;

    public PickXtra(String key, String value) {
        this.key = key;
        this.value = value;
    }
}

      

This code does not compile. In particular, I'm trying to assign an XML attribute name dynamically, but annotations require constant expressions to assign their properties. Is there a way to do this in plain XML?

+3


source to share


1 answer


Is there a way to do this in plain XML?

yes, not complicated: do Converter

.

PickXtra

class incl. itConverter

@Root(name = "PickLineXtra")
@Convert(PickXtra.PickXtraConverter.class)
public class PickXtra
{
    private final String key;
    private String value;

    public PickXtra(String key, String value)
    {
        this.key = key;
        this.value = value;
    }


    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }

    @Override
    public String toString()
    {
        return "PickXtra{" + "key=" + key + ", value=" + value + '}';
    }


    /* 
     * !===> This is the actual part <===!
     */
    static class PickXtraConverter implements Converter<PickXtra>
    {
        @Override
        public PickXtra read(InputNode node) throws Exception
        {
            /*
             * Get the right attribute here - for testing the first one is used.
             */
            final String attrKey = node.getAttributes().iterator().next();
            final String attrValue = node.getAttribute(attrKey).getValue();

            return new PickXtra(attrKey, attrValue);
        }

        @Override
        public void write(OutputNode node, PickXtra value) throws Exception
        {
            node.setAttribute(value.key, value.getValue());
        }
    }
}

      

I added a getter toString()

for testing as well. Actual parts:



  • @Convert(PickXtra.PickXtraConverter.class)

    - install the converter
  • static class PickXtraConverter implements Converter<PickXtra> { ... }

    - implementation

Testing

/* Please note the 'new AnnotationStrategy()' - it important! */
final Serializer ser = new Persister(new AnnotationStrategy());

/* Serialize */
PickXtra px = new PickXtra("ExampleKEY", "ExampleVALUE");
ser.write(px, System.out);

System.out.println("\n");

/* Deserialize */
final String xml = "<PickLineXtra ExampleKEY=\"ExampleVALUE\"/>";
PickXtra px2 = ser.read(PickXtra.class, xml);

System.out.println(px2);

      

Result

<PickLineXtra ExampleKEY="ExampleVALUE"/>

PickXtra{key=ExampleKEY, value=ExampleVALUE}

      

+2


source







All Articles