Saturday, September 19, 2015

Bài tập IXJ - Schema Validator (DOM, SAX)

Mục tiêu:

  • Căn bản schema

  • Sử dụng dụng Validator để kiểm tra tính hợp lệ của dữ liệu XML



  • DOM

  • SAX







XML Schema là dạng tài liệu theo chuẩn XML được đề xuất bởi tổ chức W3C năm 2001. XML Schema được dùng để mô tả cấu trúc và các kiểu dữ liệu của một tài liệu XML thay thế cho chuẩn DTD (Document Type Definition) trước đây. Việc này giúp định nghĩa một tài liệu XML hợp lệ cũng như các metadata cần thiết để sử dụng trong nhiều loại ứng dụng và công nghệ hiện nay như XAML, ADO.NET, WebService,… Với schema chúng ta có thể định nghĩa cấu trúc cũng như kiểu dữ liệu cho mẫu XML được rõ ràng hơn.

Ví dụ với mẫu XML sau

[sourcecode language="xml"]
<emplist>
<emp status="off">
<id>1</id>
<name>Ngo Ngo Tuong Dan</name>
</emp>
<emp status="on">
<id>2</id>
<name>Andrew Fuller</name>
</emp>
<emp status="on">
<id1>3</id1>
<name>Janet Leverling</name>
</emp>
</emplist>
[/sourcecode]

Chúng ta có thể định nghĩa schema như sau (có thể sử dụng netbean để tạo mẫu xsd)

[sourcecode language="xml"]
<?xml version="1.0"?> <!-- Một số kiểu dữ liệu
xs:string , xs:decimal , xs:integer
xs:boolean, xs:date , xs:time -->
<!-- tham chiếu đến namespace của schema-->
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="emplist">
<!-- mô tả cho kiểu phức tạp-->
<xs:complexType>
<xs:sequence>
<!-- mô tả một element/node.
maxOccurs="unbounded" ==> là không hạn chế số thẻ con
maxOccurs="1" là giá trị mặc định ==> một thẻ con duy nhất
maxOccurs="0" là thẻ rổng -->
<xs:element name="emp" maxOccurs="unbounded">
<xs:complexType>
<!-- các thẻ con của thẻ hiện tại-->
<xs:sequence>
<xs:element name="id" type="xs:integer" />
<xs:element name="name" type="xs:string" />
</xs:sequence>
<!-- thuộc tính của thẻ hiện tại-->
<xs:attribute name="status" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
[/sourcecode]

Tham khảo ghi chú trong ví dụ trên để biết thêm về xml schema
Trong Java để có thể kiểm tra tính hợp lệ của mẫu XML trên như sau:

[sourcecode language="java"]
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import javax.xml.transform.dom.DOMSource;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class EMPValidator {

public static void main(String[] args) {
try {
// create an object of DocumentBuilder class
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// parse an XML document into a DOM tree
Document document = parser.parse("src/emp.xml");
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// create an object of Source class
Source schemaFile = new StreamSource(new File("src/emp.xsd"));
// load a WXS schema, represented by a Schema instance
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// register for listening the error while XML parsing
ErrHandler err = new ErrHandler();
validator.setErrorHandler(err);
// validate the DOM tree
validator.validate(new DOMSource(document));

System.out.println("emp.xml document is valid!");
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static class ErrHandler implements ErrorHandler
{
public void warning(SAXParseException exception) throws SAXException {
System.out.println("warning: "+ exception.toString());
}

public void error(SAXParseException exception) throws SAXException {
System.out.println("error: "+ exception.toString());
}

public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatalError: "+ exception.toString());
}
}
}
[/sourcecode]

Đến đây chạy code trên chúng ta sẽ nhận được thông báo

emp.xml document is valid!

Việc quản lý lỗi trong quá trình kiểm tra sẽ do ErrorHandler xử lý như code trên.

Tương tự như vậy cho SAX

[sourcecode language="java"]
try {
System.out.println("Validating xml document with SAX");
InputSource is = new InputSource(new BufferedReader(new FileReader(xmlDocument2)));
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source src = new StreamSource(schema2);

Schema schema = sf.newSchema(src);
Validator valid = schema.newValidator();

valid.validate(new SAXSource(is));

System.out.println("Document is valid !");
System.out.println("-----------------------------------------------");
} catch (Exception ex) {
System.out.println("Document is invalid !");
System.out.println("-----------------------------------------------");
}
[/sourcecode]

No comments:

Post a Comment

Translate