Wednesday

[XML]Xử lý XML file với SAX trong java (Phần 1)


SAX, viết tắt của: the Simple API for XML:

SAX được thiết kế gồm các interface (hoặc các abstract class) thay vì các lớp xử lý cố định, có thể hiểu là lớp trên của bộ phân tích nguyên thủy. Chúng ta có thể hiện thực lại các phương thức trong các interface của SAX tùy cách sử dụng.

SAX có hai interface cơ bản là:
+ XMLReader: gồm thực hiện việc đọc file XML và phân tích file đó bằng cách gọi các phương thức của ContentHandler.
+ ContentHandler: gồm các phương thức xử lý việc nhận dữ liệu từ việc phân tích.

SAX được thiết kế theo Observer design pattern. XMLReader đóng vai trò là Subject và ContentHandler đóng vai trong là các Observer. Nhưng mỗi thực thể XMLReader chỉ cho phép đăng ký một listener.

* Sử dung XMLReader: chúng ta sẽ sử dụng hàm tạo thực thể XMLReader mặc định của lớp XMLReaderFactory.

Tạo thực thể XMLReader và gọi hàm parse:

package jbohn.example.xml;

import java.io.IOException;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class SAXexample 
{
    private final static String xmlPath = System.getProperty("user.dir");
    
    public static void main(String[] args) 
    {
        XMLReader xmlReader;
        String xmlFile = xmlPath + "\\XML_SAX.xml"; //click on xmlFile to download it
        
        try 
        {
            xmlReader = XMLReaderFactory.createXMLReader();
            xmlReader.parse(xmlFile);
            System.out.println("Parsed " + xmlFile + " sucessfully");
        }
        catch (SAXException e) 
        {
            System.out.println(xmlFile + " is not well-formed");
        } 
        catch (IOException e) 
        {
            System.out.println("Cannot acess to or read file" + xmlFile);
        }
    }
}
 
 * Sử dụng ContentHandler: Hầu hết các trường hợp chúng ta phải hiện thực lại các phương thức của interface này.

Các methods được khai bào trong ContentHandler:
package org.xml.sax;

public interface ContentHandler 
{

  public void setDocumentLocator(Locator locator);
  public void startDocument() throws SAXException;
  public void endDocument() throws SAXException;
  public void startPrefixMapping(String prefix, String uri)
   throws SAXException;
  public void endPrefixMapping(String prefix) 
   throws SAXException;
  public void startElement(String namespaceURI, String localName,
   String qualifiedName, Attributes atts) throws SAXException;
  public void endElement(String namespaceURI, String localName,
   String qualifiedName) throws SAXException;
  public void characters(char[] text, int start, int length)
   throws SAXException;
  public void ignorableWhitespace(char[] text, int start, 
   int length) throws SAXException;
  public void processingInstruction(String target, String data)
   throws SAXException;
  public void skippedEntity(String name)
   throws SAXException;

}
 
Khi chúng ta cần phân tích một file XML chúng ta sẽ hiện thực các phương thức trong ContentHandler. DefaultHandler là lớp đã hiện thực các phương thức trên. ContentHandler tùy biến (các bạn tự implement việc xử lý các thành phần trong file xml) sẽ kế thừa từ DefaultHandler hoặc implement ContentHandler. Ví dụ khi parser gặp thẻ bắt đầu nó sẽ gọi startDocument, cần gặp thẻ kết thúc nó sẽ gọi endDocument, cần đọc nội dung của trong thẻ nó đọc characters,... khi đó tùy vào mục đích các bạn sẽ hiện thực cá phương thức đó.


package jbohn.example.xml;

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

public class SaxHandler extends DefaultHandler 
{
    public void startDocument() throws SAXException 
    {
        System.out.println("start document   : ");
    }

    public void endDocument() throws SAXException 
    {
        System.out.println("end document     : ");
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException 
    {

        System.out.println("start element    : " + qName);
    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException 
    {
        System.out.println("end element      : " + qName);
    }

    public void characters(char ch[], int start, int length)
            throws SAXException 
    {
        System.out.println("start characters : "
                + new String(ch, start, length));
    }

}
 
Output: 
start element    : book
start characters :
    
start element    : author
start characters : Gambardella, Matthew
end element      : author
start characters :
    
start element    : title
start characters : XML Developer's Guide
end element      : title
start characters :
    
start element    : genre
start characters : Computer
end element      : genre
start characters :
    
start element    : price
start characters : 44.95
end element      : price
start characters :
    
start element    : publish_date
start characters : 2000-10-01
end element      : publish_date
start characters :
    
start element    : description
start characters : An in-depth look at creating applications
      with XML.
end element      : description
start characters :
 
end element      : book

Trong phần tới chúng ta sẽ tìm hiểu về một số cách hiện thức các phươn thức trong  ContentHandler.

0 comments:

Post a Comment