2

If there is a XML file like this:

<List>
    <ListItem>
        <Element1>foo</Element1>
    </ListItem>
    <ListItem>
        <Element2>another foo</Element2>
    </ListItem>
    <ListItem>
        <Element3>foo foo</Element3>
    </ListItem>
    <ListItem>
        <Element4>foooo</Element4>
    </ListItem>
    <ListItem>
        <Element5>foo five</Element5>
    </ListItem>
</List>

How can I read elements, which names are always different? The <ListItem> tag is always the same, but the elements always have different names..

I'm stuck at this point:

@Root(name = "ListItem")
public class ListItem
{
    @Element(name = ?????)
    String Element;
}

And in the end I want to use it like this:

...

    @ElementList(name = "List")
    List<ListItem> Items;

...

Regards

ollo
  • 24,797
  • 14
  • 106
  • 155

1 Answers1

0

If the elements vary that much, you'll have to do some work manually - however, it's not much:

  1. Implement a Converter, eg. ListItemConverter
  2. Enable it by @Convert annotation
  3. Set AnnotationStrategy for your Serializer

@Root(name = "List")
public class ExampleList
{
    @ElementList(inline = true)
    private List<ListItem> elements;

    /* ... */


    @Root(name = "ListItem")
    @Convert(ListItemConverter.class)
    public static class ListItem
    {
        private final String text;


        public ListItem(String text)
        {
            this.text = text;
        }

        /* ... */
    }

    static class ListItemConverter implements Converter<ListItem>
    {
        @Override
        public ListItem read(InputNode node) throws Exception
        {
            final InputNode child = node.getNext();

            if( child != null )
            {
                /*
                 * If you need the 'Element*' too:
                 * child.getName()
                 */
                return new ListItem(child.getValue());
            }

            return null;
        }


        @Override
        public void write(OutputNode node, ListItem value) throws Exception
        {
            // Implement if you also need to write ListItem's
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }

}

Don't forget to set the AnnotationStrategy, else the @Convert wont work:

Serializer ser = new Persister(new AnnotationStrategy());
// ...
ollo
  • 24,797
  • 14
  • 106
  • 155