在SimpleXML(java)中动态分配属性名称

时间:2014-08-11 15:21:27

标签: java xml simple-framework

我有以下课程:

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 个答案:

答案 0 :(得分:2)

  

有没有办法用简单的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());
        }
    }
}

为了测试目的,我添加了getter和toString()。实际部分是:

  1. @Convert(PickXtra.PickXtraConverter.class) - 设置转换器
  2. static class PickXtraConverter implements Converter<PickXtra> { ... } - 实施
  3. 测试

    /* 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}