Hướng dẫn thực hành XmlPullParser đọc dữ liệu từ file xml trong android

Code: Default | Auth: 03cd82

Bước 1: Tạo project mới, tạo file xml dữ liệu để thực hành

- Sau khi tạo project mới, bạn chuyển chế độ view thư mục về dạng Project

Tạo file xml trong thư mục asset

Bước 2: Soạn nội dung file xml dữ liệu

<?xml version="1.0" encoding="utf-8" ?>
<products>
    <product>
        <name>Điện thoại</name>
        <price>300000</price>
    </product>
    <product>
        <name>Máy tính</name>
        <price>100000</price>
    </product>
    <product>
        <name>Tivi</name>
        <price>5000000</price>
    </product>
</products>

Bước 3: Tạo file DTO để map dữ liệu khi đọc được


public class ProductDTO {
    String name;
    int price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    // viết phương thức toString cho đối tượng
    // để dùng cho trường hợp sử dụng ArrayAdapter
    public String toString(){
        return  "Name: " + this.name + ", Price: " + this.price;
    }
}

Bước 4: Tạo file ProductLoader để load dữ liệu

public class ProductLoader {
    List<ProductDTO> productDTOList = new ArrayList<ProductDTO>();
    ProductDTO productDTO;
    String textContent;

    public List<ProductDTO> getProductDTOList(InputStream inputStream) {

        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            // truyền nguồn dữ liệu
            parser.setInput(inputStream, null);
            // xác định event type
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                // viết code xử lý ở đây
                String tagName = parser.getName();
                Log.d("zzzzz", "Tag name =  " + tagName +
                        ", Độ sâu của thẻ = " + parser.getDepth() + ", event = " + eventType);
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        // bắt đầu vào 1 thẻ
                        if (tagName.equalsIgnoreCase("product")) {
                            productDTO = new ProductDTO();
                        }
                        break;
                    case XmlPullParser.TEXT:
                        textContent = parser.getText();
                        break;

                    case XmlPullParser.END_TAG:
                            if(productDTO != null){
                                if(tagName.equalsIgnoreCase("product"))
                                    productDTOList.add(productDTO);
                                else if (tagName.equalsIgnoreCase("name"))
                                    productDTO.setName( textContent );
                                else if (tagName.equalsIgnoreCase("price"))
                                    productDTO.setPrice( Integer.parseInt(textContent) );
                            }


                        break;
                    default:
                        Log.d("zzzz", "eventType khác: " + eventType + ", tag = " + tagName);
                        break;
                }


                // viết lệnh chuyển event type để vòng lặp không bị treo
                // để ở cuối cùng của lệnh while
                eventType = parser.next();
            }


        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return productDTOList;
    }
}

Bước 5: Trong activity viết code lấy dữ liệu ghi ra log

        List<ProductDTO> list = null;
        ProductLoader loader = new ProductLoader();

        try {
            InputStream inputStream = getAssets().open("products.xml");

            list = loader.getProductDTOList( inputStream );

            for(int i = 0; i< list.size(); i++){
                Log.d("zzz", "San pham: " + list.get(i).toString()   );
            }
           


        } catch (IOException e) {
            e.printStackTrace();
        }

Bước 6: Chạy thử chương trình và xem log.

Ở activity đã lấy được danh sách dữ liệu thì bạn có thể tạo adapter để hiển thị lên listview (tham khảo trong file đính kèm)

 

Tập tin đính kèm bài viết: