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

时间:2016-10-20 06:49:22

标签: java android xml sax saxparser

我有一个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>

为了保存数据解析,我创建了一个类Department和一个集合ArrayList <Department>,以便将这些类保存在那里。该课程如下:

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解析器在类的每个实例中都有效Departament只有他的女儿标记product id并放在特定的ArrayList <Integer>

1 个答案:

答案 0 :(得分:0)

试试这个。

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