[英]Parsing XML using android sax parser
以下是本教程中我嘗試使用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
課程。 父級具有一個字段,該字段是諸如此類的子級對象的列表。
父級
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
}
因此,我創建了一個Parent對象來存儲解析后的數據。 在下面的代碼中,我可以獲取parent
的name
和id
元素,但無法弄清楚如何解析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 ;
}
}
parent.getChild("child").getChild("id").setEndTextElementListener(
new EndTextElementListener() {
public void end(String body) {
current.setChildId(body);
}
});
parent.getChild("child").getChild("name").setEndTextElementListener(
new EndTextElementListener() {
public void end(String body) {
current.setChildName(body);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.