Thứ Bảy, 2 tháng 8, 2014

Tổng quát về DOM

I. DOM 

1. DOM là gì?

Dom là chữ viết tắt từ tiếng Anh Document Object Model ("Mô hình Đối tượng Tài liệu"), là một API (Giao diện lập trình ứng dụng). Thường thường DOM, có dạng một cây cấu trúc dữ liệuđược dùng để truy xuất các tài liệu dạng HTML và XML. Mô hình DOM độc lập với hệ điều hành và dựa theo kỹ thuật lập trình hướng đối tượng để mô tả tài liệu. (Theo wikipedia)

2. Các ưu điểm của DOM.

- Cung ứng khả năng truy cập vào nhiều tài liệu.

- DOM có khả năng quản lý các cấu trúc dữ liệu phức tạp.

- Cho phép thay đổi tài liệu.

- Cho phép nhiều phương thức truy cập vào cùng một tài liệu.

3. Các thành phần của DOM.
- DOM gồm nhiều các cái nút theo hình cây (tree format) vì vậy DOM biểu dễn các dữ liệu XML trong cùng một cách.
- ĐÓM tạo ra một "cấu trúc cây" giống như cấu trúc của file XML, bắt đầu với một node root tương đương với root element của tệp XML sẽ được biểu diễn như một cái nút và các thành phần có trong element đó sẽ là các node con.

4. Làm việc với DOM.

- Gần giống như khi làm việc với SAX thì ở DOM ta sẽ tạo ra Document Builder từ Document Builder Factory.

- Để làm việc với DOM ta có các interface của DOM trong ảnh dưới đây
.


DEMO:

Tạo mới một project với tên OverView_DOM và tạo ra một file tomcat_users.xml như dưới đây. Ở bài demo này chúng ta sẽ lấy ra số thẻ user trong file xml này.

<?xml version="1.0" encoding="UTF-8"?>

<tomcat-users>
    <role rolename="tomcat"/>
    <role rolename="role1"/>
    <user username="tomcat" password="tomcat" roles="tomcat"/>
    <user username="both" password="tomcat" roles="tomcat,role1"/>
    <user username="role1" password="tomcat" roles="role1"/>
    
    <user password="admin" role="manager-script,admin" username="admin"/>
</tomcat-users>

Tiếp đó chúng ta code trong hàm main như dưới:

public static void main(String[] args) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbf.newDocumentBuilder();
            
            Document document = builder.parse(new File("D:\\NetBean\\Overview_DOM\\src\\tomcat-users.xml"));
            NodeList elementsByTagName = document.getElementsByTagName("user");
            
            System.out.println(elementsByTagName.getLength());
        } catch (SAXException | IOException | ParserConfigurationException ex) {
            Logger.getLogger(Overview_DOM.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

Ta cần import các class, interface sau:

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException

Đây là source code của bài demo này.



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

Đăng nhận xét