Empty entry in ElementList SimpleXML

喜欢而已 提交于 2019-12-01 22:40:29

You can check for empty elements manually:

@Root(name = "entries")
@Convert(List.ListConverter.class) // Set the converter
public class List
{
    @ElementList(required = false, entry = "entry", inline = true, empty = true)
    private java.util.List<Entry> entries;


    public void add(Entry e)
    {
        // Just for testing
        entries.add(e);
    }



    static class ListConverter implements Converter<List>
    {
        @Override
        public List read(InputNode node) throws Exception
        {
            List l = new List();
            InputNode child = node.getNext("entry");

            while( child != null)
            {
                if( child.isEmpty() == true ) // child is an empty tag
                {
                    // Do something if entry is empty
                }
                else // child is not empty
                {
                    Entry e = new Persister().read(Entry.class, child); // Let the Serializer read the Object
                    l.add(e);
                }

                child = node.getNext("entry");
            }

            return l;
        }


        @Override
        public void write(OutputNode node, List value) throws Exception
        {
            // Not required for reading ...
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}

How to use:

Serializer ser = new Persister(new AnnotationStrategy()); // Set AnnotationStrategy here!
List l = ser.read(List.class, yourSourceHere);

Documentation:

To avoid the error in parse do one should place annotation tags @set e @get

@Root(name = "entries", strict = false)
public class List {

@set:ElementList(required = false, entry = "entry", inline = true, empty = true)
@get:ElementList(required = false, entry = "entry", inline = true, empty = true)
    private List<Entry> entries;

}

@Root
public class Entry {

    @set:Element(name = "entry_id", required = true)
    @get:Element(name = "entry_id", required = true)
    private long id;

    @set:Element(name = "text", required = true)
    @get:Element(name = "text", required = true)
    private String Text;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!