Parsing XML using android sax parser
below is a sample structure of the XML I'm trying to parse using the Android SAX parsing approach in this tutorial.
<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>
I have two classes named Parent
and Child
. Parent has a field which is a list of Child objects, such as this.
Parent
public class Parent {
private String id;
private String name;
private List<Child> childList;
//constructor, getters and setters
// more code
}
Child
public class Child {
private String id;
private String name;
//constructor, getters and setters
// more code
}
So I created a Parent object to store the parsed data. In the code below I can get the name
and id
element of parent
but I cant figure out how to parse the child
elements and their own child elements. I dont know if this is the right way to accomplish what I'm trying to do.
Can someone show me a way?
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);
开发者_如何学JAVA }
});
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);
}
});
精彩评论