android - ElementList SimpleXML 中的空条目

标签 android simple-framework

我的问题很简单,但我什么也找不到。

我有一个列表类和一个用于 XML 序列化的入口类:

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

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

@Root
public class Entry {

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

    @Element(name = "text", required = true)
    private String Text;
}

我正在尝试解析此 XML,它在列表中没有任何条目:

<entries>
   <entry />
<entries>

返回如下错误:

W/System.err(3335): org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.Element(data=false, name=entry_id, required=true, type=void) on field 'id' private long com.android.apps.model.Entry.id for class com.android.apps.model.Entry at line 2

我做错了什么? ElementList 设置为空 = true 和 required = false。 有人可以帮忙吗?

最佳答案

您可以手动检查空元素:

@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.");
        }
    }
}

使用方法:

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

文档:

关于android - ElementList SimpleXML 中的空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21581789/

相关文章:

java - 如何从 xsd 模式生成 simple-xml java 注释对象

android - 如果滚动位置为 0,ViewPager2 中的 fragment 不会响应点击

java.net.ConnectException : failed to connect to/192. 168.10.110 连接失败:ECONNREFUSED(连接被拒绝

Android - 如何在滚动 NestedScrollView 时缩放图像?

java - 将 Map 转换为内联元素、文本 XML

android - 是否可以同时使用 JAXB 和简单 XML?

java - 如何摆脱缩进以及如何告诉 Simple xml 框架,在序列化对象时不要转换“to”

java - 如何使用简单 XML 序列化 Map<String, String>?

android - 使用 ionic 框架,本地镜像在 chrome 中完美显示,但在我的 android 手机中不显示

android - cocos2d-x中tableview的cell touch误操作