Frage

I'm discovering Simple XML and try to serialize this simple class :

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

  // some methods and attributes...
}

To :

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

There is the @Attribute annotation but this can't convert the set to a string. Simple XML provides some "transformers" for doing this job but I can't find any example.

Thanks

War es hilfreich?

Lösung

Instead of transformers, better use a Converter. You can use them on a class as well as on single fields. Basically a Converter is the implementation of "how to translate the annotated object into xml nodes".

Here's an example, using a Converter for the class 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());
        }
    }
}

Note: Converter's can be implemented as ordinary classes too, i used an inner one for this example, to keep everything together.

How to use:

Div d = new Div();

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

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

For deserialization, just implement the Converter's read() method. To get the attributes value back to a set use a StringTokenizer.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top