简单框架XML反序列化

时间:2013-10-23 13:02:33

标签: java android parsing simple-framework serializer

如果我改变我的Data.xml文件现在包含两个分支而不是一个分支,我该如何捕获数组中的对象?

当前的MainActivity.java文件:

    try {
        Serializer serializer = new Persister();
        AssetManager assetManager = getAssets();
        InputStream inputStream = assetManager.open("data.xml");
        Data d = serializer.read(Data.class, inputStream);
        System.out.println(d.getPokemon());
    } 
    catch (Exception e) {
        e.printStackTrace();
    }

当前Data.java文件:

@Root(name="Data")
public class Data {

    @Element(name="pkmn")
    private Pokemon pokemon;

    public Pokemon getPokemon() {
        return pokemon;           
    }
}

当前的Pokemon.java文件:

public class Pokemon implements Serializable{


    @Element(name="nm")
    private String name;
    @Element(name="tp")
    private String type;
    @Element(name="ablt")
    private String abilities;
    @Element(name="wkns")
    private String weakness;
    @Element(name="img")
    private String image;

    public Pokemon(){}
    public Pokemon(String n, String t, String a, String w, String i){
        name = n;
        type = t;
        abilities = a;
        weakness = w;
        image = i;
    }
    public String toString() {...}

当前Data.xml文件:

<?xml version = "1.0" encoding = "utf-8" ?>
<Data>
<pkmn> 
        <nm>Beedrill</nm> 
        <tp>bug</tp> 
        <ablt>swarm</ablt>
        <wkns>fire</wkns>
        <img>beedrill</img>
    </pkmn> 
<Data>

新Data.xml文件:

<?xml version = "1.0" encoding = "utf-8" ?>
<Data>

    <pkmn> 
        <nm>Beedrill</nm> 
        <tp>bug</tp> 
        <ablt>swarm</ablt>
        <wkns>fire</wkns>
        <img>beedrill</img>
    </pkmn> 

    <pkmn> 
        <nm>Blastoise</nm> 
        <tp>water</tp> 
        <ablt>torrent</ablt>
        <wkns>electric</wkns>
        <img>blastoise</img>
    </pkmn> 
</Data>

1 个答案:

答案 0 :(得分:2)