简单的XML和HashSet

时间:2013-12-30 16:14:25

标签: java xml serialization simple-framework

我正在发现Simple XML并尝试序列化这个简单的类:

public class Div
{
  private Set< String > _classes = new HashSet< String >() {{
    add( "a" );
    add( "b" );
    add( "c" );
  }};

  // some methods and attributes...
}

致:

<div class="a b c">
</div>

有@Attribute注释,但这不能将集合转换为字符串。简单的XML为完成这项工作提供了一些“变形金刚”,但我找不到任何例子。

由于

1 个答案:

答案 0 :(得分:3)

而不是变形金刚,更好地使用Converter。您可以在类和单个字段上使用它们。基本上,转换器是“如何将带注释的对象转换为xml节点”的实现。

以下是一个示例,Converter用于课程Div

@Root(name = "div")
@Convert(value = Div.DivConverter.class) // Set the Converter for this class
public class Div
{
    private Set< String> _classes = new HashSet< String>()
    {
        {
            add("a");
            add("b");
            add("c");
        }
    };

    // some methods and attributes...

    public Set<String> getClasses()
    {
        return _classes;
    }

    // ...


    /*
     * Converter implementation.
     */
    static class DivConverter implements Converter<Div>
    {
        @Override
        public Div read(InputNode node) throws Exception
        {
            /*
             * Not required for writing, therefore not implemented int this
             * example.
             */
            throw new UnsupportedOperationException("Not supported yet.");
        }



        @Override
        public void write(OutputNode node, Div value) throws Exception
        {
            StringBuilder sb = new StringBuilder(); // Used to store the set's values in string-form
            Set<String> cl = value.getClasses();

            if( cl.isEmpty() == false ) // Check if classes is empty - nothing to do if so
            {
                int pos = 0;    // Keep trac of current position (not to add an blank char for last entry)
                final int size = cl.size();

                for( String s : cl )    // Iterate over all entries of classes
                {
                    sb.append(s);   // Append the entry to buffer

                    if( (pos++) < size - 1 )
                    {
                        sb.append(' '); // If not last entry, add a blank
                    }
                }
            }

            // Finally add the attribute 'class' with the content, to the 'div'-node
            node.setAttribute("class", sb.toString());
        }
    }
}

注意:转换器也可以作为普通类实现,我在本例中使用了内部类,以便将所有内容保存在一起。

使用方法:

Div d = new Div();

File f = new File("test.xml");

Serializer ser = new Persister(new AnnotationStrategy()); /* Don't miss AnnotationStrategy!! */
ser.write(d, f);

对于反序列化,只需实现Converter的read()方法。要将属性值返回到集合,请使用StringTokenizer

相关问题