我正嘗試使用simpleXML將XML文件反序列化爲Java對象。一切工作正常,直到我不得不使用ElementMap。 這是我的XML文件的一部分:將XML元素反序列化爲Java地圖
<piece composer="Me" date="Yesterday" title="Important work">
<editions>
<edition name="My Name" date="2015" description="A single page">
<pages>
<page fileName="page01.jpg" />
</pages>
</edition>
<edition name="My Name again" date="2015" description="Another single page">
<pages>
<page fileName="page01.jpg" />
</pages>
</edition>
</editions>
<layers>
<layer name="Annotations" color="#FF0000" description="Empty" id="anno" />
<layer name="Information" color="#00FF00" description="Empty" id="info" />
</layers>
</piece>
相應的Java類看起來是這樣的:
@Root
public class Piece {
@Attribute
private String composer;
@Attribute
private String title;
@Attribute
private String date;
@ElementList
private List<Edition> editions;
@ElementMap(key = "id", attribute = true) // Relevant
private Map<String, Layer> layers; // Lines
public static Piece loadFromAsset(Context context, String fileName) throws Exception {
Serializer serial = new Persister();
return serial.read(Piece.class, context.getResources().getAssets().open(fileName));
}
}
最後層類:
public class Layer {
@Attribute
private String id;
@Attribute
private String name;
@Attribute
private String description;
@Attribute
private String color;
}
加載XML文件後地圖包含兩個鍵,但它們都指向null
而不是實際的層對象。
非常感謝!我用一種幾乎完全相同的語法結束了使用方法A的過程。 其他解決方案並不少,但簡單美觀。 ;-) – sonovice