使用android sax解析器解析XML
问题描述:
下面是一个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 ;
}
}
答
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);
}
});