Search code examples
javaandroidxmlsaxsaxparser

How to use the SAX parser to save the only child elements and storing them in the collection?


I have a xml file:

<shop>
    <department number= "1" name="unknown">
        <product id="1"/>
        <product id="2"/>
        <product id="3"/>
    </department>
    <department number= "2" name="unknown">
        <product id="4"/>
        <product id="5"/>
        <product id="6"/>
    </department>
    <department number= "3" name="unknown">
        <.../>
    </department>
</shop>

To save the data parsing, I created a class Department and a collection ArrayList <Department>, to keep these classes there. The class looks like this:

class Department {
    String number;
    String name;
    ArrayList<Integer> productId = new ArrayList<>(); // collection for storage "attribut id of product"
    //constructor
    public Department(String n, String na, ArrayList<Integer> pr) {
        this.number = n;
        this.name = na;
        this.productId = pr;
    }
}

How do I set the SAX-parser to work in each instance of the class Departament got only his daughter tags product id and placed in a particular ArrayList <Integer>?


Solution

  • Try this.

    public class Department {
        final String number;
        final String name;
        final List<Integer> products = new ArrayList<>();
    
        Department(String number, String name) {
            this.number = number;
            this.name = name;
        }
    }
    

    And

    File input = new File("shop.xml");
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    List<Department> departments = new ArrayList<>();
    parser.parse(input, new DefaultHandler() {
        Department department = null;
        @Override
        public void startElement(String uri,
            String localName, String qName, Attributes attributes)
            throws SAXException {
            switch (qName) {
            case "department":
                department = new Department(
                    attributes.getValue("number"),
                    attributes.getValue("name"));
                departments.add(department);
                break;
            case "product":
                department.products.add(Integer.parseInt(attributes.getValue("id")));
                break;
            }
        }
    });