views:

26

answers:

0

Hi, below is a sample structure of the xml I'm trying to parse using the Android SAX parsing approach in this tutorial (http://www.ibm.com/developerworks/opensource/library/x-android/index.html#list8).

<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.

public class Parent{
  private String id;
  private String name;
  private List<Child> childList;

 //constructor, getters and setters
  ...
}

public class Child{
  private String id;
  private String name;

  //constructor, getters and setters
  ...
}

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);
            }
        });
        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 ;
    }
}