Динамически назначать имя атрибута в SimpleXML (Java)

У меня есть следующий класс:

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;
    }
}

Этот код не компилируется. В частности, я пытаюсь назначить имя атрибута XML динамически, но аннотации требуют константных выражений для присвоения их свойств. Есть ли способ сделать это в простом XML?

1 ответ

Решение

Есть ли способ сделать это в простом XML?

да, и не сложно: реализовать Converter,

PickXtra класс вкл. его Converter

@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());
        }
    }
}

Я добавил геттер и toString() в целях тестирования. Фактические части:

  1. @Convert(PickXtra.PickXtraConverter.class) - установить конвертер
  2. static class PickXtraConverter implements Converter<PickXtra> { ... } - реализация

тестирование

/* Please note the 'new AnnotationStrategy()' - it's 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);

Результат

<PickLineXtra ExampleKEY="ExampleVALUE"/>

PickXtra{key=ExampleKEY, value=ExampleVALUE}
Другие вопросы по тегам