如何使用 SAX 解析器保存唯一的子元素并将它们存储在集合中?

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

我有一个 xml 文件:

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

为了保存数据解析,我创建了一个 class Department 和一个集合 ArrayList <Department>,以将这些 class 保存在那里。 class 看起来像这样:

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

如何将 SAX 解析器设置为在 class Departament 的每个实例中工作只得到他的女儿标签 product id 并放置在特定的 ArrayList <Integer>

试试这个。

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

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