0

Given an xml file like this one, how would I go about parsing this data into an arraylist?

<Providers>
  <CarDealer name="BEFORWARD" id="1">
    <CarMake name="Toyota" id="20" stype="se01">
      <CarModel name="Belta" id="21"/>
      <CarModel name="RunX" id="22"/>
      <CarModel name="Corolla" id="23"/>
    </CarMake>
    <CarMake name="Nissan" id="30" stype="se02">
      <CarModel name="Murano" id="31"/>
      <CarModel name="Pathfinder" id="32"/>
      <CarModel name="Navara" id="33"/>
    </CarMake>
  </CarDealer>

Parsed data should be stored like this in arraylist:

(stype, id, CarMake_name, id, CarModel_name, id, CarModel_name, id, CarModel_name)
(stype, id, CarMake_name, id, CarModel_name, id, CarModel_name, id, CarModel_name)

Using SAXParser, this is what I tried to do but my arraylist is not showing anything when I print it out. Any help and tips will be appreciated; am a newbie to Android development:

public class SAXXMLHandler extends DefaultHandler {
private static List<Service> services = new ArrayList<Service>();
private Service serv = null;
public String text = null;

public List<Service> getService() {

    return services;
}

@Override
// A start tag is encountered.
public void startElement(String uri, String localName, String qName, Attributes attributes)
    throws SAXException {
    switch (qName) {
        // Create a new Service.
        case "CarMake": {
            serv = new Service();
            serv.setID(Integer.parseInt(attributes.getValue("id")));
            serv.setName(attributes.getValue("name"));
            serv.setStype(attributes.getValue("stype"));
            break;
        }
    }
}

public void endElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    switch (qName) {
        case "CarMake": {
            // The end tag of an service was encountered, so add the service to the list.
            services.add(serv);
            break;
        }
        case "CarModel": {
            serv.setName(attributes.getValue("name"));
            serv.setID(Integer.parseInt(attributes.getValue("id")));

            break;
        }
    }
} 
2
  • Possible duplicate of Android - Parsing XML into an ArrayList Commented Dec 12, 2017 at 9:31
  • @minasameh umhm not really. I feel it is slightly different from mine because I have two objects for CarMake that contain child nodes CarModel. Iterating through them and adding the nodes to the arraylist is my challenge. But thanks for the link; have gotten something from it. Commented Dec 12, 2017 at 9:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.