我是简单 xml 库的新手。我真的很喜欢它,但我有一个问题。
这是我的类(已删除一些代码以使其更简洁):
@Root
@ElementList
public class MyArrayList<E> extends ArrayList<E>{
public void ToXml() throws Exception{
Serializer serializer = new Persister();
File file = new File("somewhere in my file system");
serializer.write(this, file);
}
}
-
@Root
public abstract class MediaEntry implements Serializable {
private static final long serialVersionUID = 1L;
@Element
public String Title;
@Element
public String Description;
@Element
public String Url;
@Element
public String LocalPath;
public MediaEntry(String title, String description,
String url, String localPath) {
Title= title;
Description= description;
Url= url;
LocalPath= localPath;
}
}
-
public class VideoEntry extends MediaEntry {
private static final long serialVersionUID = 1L;
public VideoEntry(String title, String description,
String url, String localPath) {
super(title, description, url, localPath);
}
}
当我实例化 MyArrayList 添加一些 VideoEntries 并调用 ToXml 时,我只得到一个空根,即。
<MyArrayList />
如何解决这个问题?这与 MyArrayList 是通用的这一事实有关吗?
最佳答案
列表必须是元素的成员(并且没有单独的类)才能获得所需的行为,您可以内联设置 ElementList,因此没有父元素。
@Root
public class MyArrayList<E> {
@ElementList(inline=true)
ArrayList<E> list = new ArrayList<E>();
public boolean add(E entry) {
return list.add(entry);
}
public void ToXml() throws Exception {
Serializer serializer = new Persister();
File file = new File("somewhere in my file system");
serializer.write(this, file);
}
}
只是想到了另一个可能更好的解决方案(您可以访问所有列表函数 - 但我不确定是否有任何副作用,所以我保留原来的解决方案)
@Root
public class MyArrayList<E> extends ArrayList<E> {
@ElementList(inline=true)
MyArrayList<E> list = this;
public void ToXml() throws Exception {
Serializer serializer = new Persister();
File file = new File("somewhere in my file system");
serializer.write(this, file);
}
}
要反序列化,您必须声明 SimpleXML,哪个元素用于哪个构造函数参数:
@Root
public abstract class MediaEntry implements Serializable {
private static final long serialVersionUID = 1L;
@Element
public String Title;
@Element
public String Description;
@Element
public String Url;
@Element
public String LocalPath;
public MediaEntry(@Element(name = "Title") String title,
@Element(name = "Description") String description,
@Element(name = "Url") String url,
@Element(name = "LocalPath") String localPath) {
Title = title;
Description = description;
Url = url;
LocalPath = localPath;
}
}
顺便说一句,如果您刚刚开始 Java 编程,您可能会考虑阅读 Java 代码约定 - 以大写字母开头方法和变量名不是一个好习惯(这样您可以防止养成坏习惯;- ))
关于java - Android 上的简单 XML - 类 MyArrayList<E> 扩展了 ArrayList<E>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834980/