XML解析套件 - Simple
最近想找個類似 GSON 的 XML 解析套件,
發現 GSON 真是太強了,
大部分的 XML 解析套件實在有夠難用,
勉強找到一款堪用的,
但是用起來跟 GSON 還是差了十萬八千里,
但是官網範例寫的比 GSON 好就是了,
官網已經有非常詳細的教學,
這篇主要會稍微提一下關於 List 的部分,
以下是一個 XML 的例子
<parent name="john" id="1">
<children>
<child id="2" name="tom">
<parent ref="1"/>
</child>
<child id="3" name="dick">
<parent ref="1"/>
</child>
<child id="4" name="harry">
<parent ref="1"/>
</child>
</children>
</parent>
以上 XML 只要使用 以下 Bean 就可以成功讀取
@Root
public class Parent {
private List<Child> children;
private String name;
@Attribute
public String getName() {
return name;
}
@Attribute
public void setName(String name) {
this.name = name;
}
@Element
public void setChildren(List<Child> children) {
this.children = children;
}
@Element
public List<Child> getChildren() {
return children;
}
public void addChild(Child child) {
children.add(child);
}
}
@Root
public class Child {
private Parent parent;
private String name;
public Child() {
super();
}
public Child(Parent parent) {
this.parent = parent;
}
@Attribute
public String getName() {
return name;
}
@Attribute
public void setName(String name) {
this.name = name;
}
@Element
public Parent getParent() {
return parent;
}
@Element
public void setParent(Parent parent) {
this.parent = parent;
}
}
其中要注意的是Child
的父節點<children>
是必須的,
不然讀不到,
還有,
如果要implements Serializable
必須使用Serializer mSerializer = new Persister();
來建構,
這是我今天使用後的一些心得記錄。