Thứ Năm, 31 tháng 7, 2014

Apply Filter Demo

Tạo một ứng dụng với tên Demo_Filter, sau đó ta tạo ra một file xml với tên Employee.xml như dưới:

<?xml version="1.0" encoding="UTF-8"?>
<personal>
    <employee emid="332" depid="24" shift="night" status="contact">
        Jenny Berman
    </employee>
    <employee emid="994" depid="24" shift="day" status="donotcontact">
        Andrew Fule
    </employee>
    <employee emid="948" depid="3" shift="night" status="contact">
        Anna Bangle
    </employee>
    <employee emid="1032" depid="3" shift="day" status="contact">
        David Baines
    </employee>
</personal>

Sau đó ta tạo một lớp Java với tên JavaFilter và cho nó extends XMLFilterImpl sau đó viết vào đoạn code như bên dưới:



package filter_demo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Nguyen Minh An
 */
public class DataParser extends DefaultHandler {

    private boolean valueIsProcessed;

    @Override
    public void startElement(String string, String string1, String string2, Attributes atrbts) throws SAXException {
        if (string1.equals("employee")) {
            if (atrbts.getValue("status").equals("contact") && atrbts.getValue("depid").equals("24")) {
                valueIsProcessed = true;
            }
        }
        super.startElement(string, string1, string2, atrbts);
    }

    @Override
    public void characters(char[] chars, int i, int i1) throws SAXException {
        if (valueIsProcessed == true) {
            System.out.println("Name:" + new String(chars, i, i1));
            valueIsProcessed = false;
        }
    }

}

Và cuối cùng ở hàm main ta khai báo như sau:

public static void main(String[] args) {
        try {
            XMLReader reader = XMLReaderFactory.createXMLReader();
            DataFilter df = new DataFilter();
            df.setParent(reader);
            df.setContentHandler(new DataParser());

            df.parse("D:\\NetBean\\Filter_Demo\\src\\Employee.xml");
        } catch (IOException | SAXException ex) {
            Logger.getLogger(Filter_Demo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

Vậy là chúng ta đã tạo xong demo. Các bạn có thể download source code tại đây


Nhận xét:
- Sử dụng filter khá dễ dàng.
- Khi sử dụng filter sẽ giúp cho các parser được xử lý nhanh hơn do đã được filter xử lý trước.
- Ta có thể chỉnh sửa nguồn dữ liệu của file xml mà không làm thay đổi file gốc.

Không có nhận xét nào:

Đăng nhận xét