0
下面是一個XML示例結構,我試圖在此tutorial中使用Android SAX解析方法進行解析。使用android sax解析器解析XML
<root>
<parent>
<id></id>
<name></name>
<child>
<id></id>
<name></name>
</child>
<child>
<id></id>
<name> </name>
</child>
</parent>
<parent>
<id></id>
<name></name>
<child>
<id></id>
<name></name>
</child>
</parent>
...
</root>
我有一個名爲Parent
和Child
兩班。 Parent有一個字段,它是一個Child對象的列表,比如這個。
家長
public class Parent {
private String id;
private String name;
private List<Child> childList;
//constructor, getters and setters
// more code
}
兒童
public class Child {
private String id;
private String name;
//constructor, getters and setters
// more code
}
所以我創建了一個父對象來存儲解析數據。在下面的代碼中,我可以得到和id
元素parent
,但我無法弄清楚如何解析child
元素和他們自己的子元素。我不知道這是否是完成我想要做的事情的正確方法。
有人可以告訴我一個方法嗎?
public class AndroidSaxFeedParser extends BaseFeedParser {
public AndroidSaxFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Parent> parse() {
final Parent current = new Parent();
RootElement root = new RootElement("root");
final List<Parent> parents = new ArrayList<Parent>();
Element parent = root.getChild("parent");
parent.setEndElementListener(new EndElementListener() {
public void end() {
parents.add(current.copy());
}
});
parent .getChild("id").setEndTextElementListener(
new EndTextElementListener() {
public void end(String body) {
current.setId(body);
}
});
parent .getChild("name").setEndTextElementListener(
new EndTextElementListener() {
public void end(String body) {
current.setName(body);
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8,
root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
return parents ;
}
}