Wednesday, August 25, 2010

Writing MySQL Scripts with PHP and PDO

Writing MySQL Scripts with PHP and PDO

Paul DuBois
paul@kitebird.com

Document revision: 1.01
Last update: 2008-05-07

Table of Contents


PHP makes it easy to write scripts that access databases, enabling you to create dynamic web pages that incorporate database content. PHP includes several specialized database-access interfaces that take the form of separate sets of functions for each database system. There is one set for MySQL, another for InterBase, another for PostgreSQL, and so forth. However, having a different set of functions for each database makes PHP scripts non-portable at the lexical (source code) level. For example, the function for issuing an SQL statement is named mysql_query(), ibase_query(), or pg_exec(), depending on whether you are using MySQL, InterBase, or PostgreSQL.

In PHP 5 and up, you can avoid this problem by using the PHP Data Objects (PDO) extension. PDO supports database access in an engine-independent manner based on a two-level architecture:

  • The top level provides an interface that consists of a set of classes and methods that is the same for all database engines supported by PDO. The interface hides engine-specific details so that script writers need not think about which set of functions to use.
  • The lower level consists of individual drivers. Each driver supports a particular database engine and translates between the top-level interface seen by script writers and the database-specific interface required by the engine. This provides you the flexibility of using any database for which a driver exists, without having to consider driver-specific details.
This architectural approach has been used successfully with other languages--for example, to develop the DBI (Perl, Ruby), DB-API (Python), and JDBC (Java) database access interfaces. It's also been used with PHP before: PHPLIB, MetaBase, and PEAR DB are other packages that provide a uniform database-independent interface across different engines.

I have written elsewhere about using the PEAR DB module for writing PHP scripts that perform database processing in an engine-independent manner (see "Resources"). This document is similar but covers PDO instead. The examples use the driver for MySQL.

Preliminary Requirements


PDO uses object-oriented features available only in PHP 5 and up, so you must have PHP 5 or newer installed to use PDO for writing scripts that access MySQL.

PDO uses classes and objects to present an object-oriented interface. This article assumes that you are familiar with PHP's approach to object-oriented programming. If you are not, you may wish to review the "Classes and Objects" chapter of the PHP Manual.

Writing PDO Scripts


Scripts that use the PDO interface to access MySQL generally perform the following operations:

  • Connect to the MySQL server by calling new PDO() to obtain a database handle object.
  • Use the database handle to issue SQL statements or obtain statement handle objects.
  • Use the database and statement handles to retrieve information returned by the statements.
  • Disconnect from the server when the database handle is no longer needed.
The next sections discuss these operations in more detail.

Connecting to and Disconnecting from the MySQL Server


To establish a connection to a MySQL server, specify a data source name (DSN) containing connection parameters, and optionally the username and password of the MySQL account that you want to use. To connect to the MySQL server on the local host to access the test database with a username and password of testuser and testpass, the connection sequence looks like this:

   $dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass");
For MySQL, the DSN is a string that indicates the database driver (mysql), and optionally the hostname where the server is running and the name of the database you want to use. Typical syntax for the DSN looks like this:
   mysql:host=host_name;dbname=db_name
The default host is localhost. No default database is selected if dbname is omitted.

The MySQL driver also recognizes port and unix_socket parameters, which specify the TCP/IP port number and Unix socket file pathname, respectively. If you use unix_socket, do not specify host or port.

For other database engines, the driver name is different (for example, pgsql for PostgreSQL) and the parameters following the colon might be different as well.

When you invoke the new PDO() constructor method to connect to your database server, PDO determines from the DSN which type of database engine you want to use and acesses the low-level driver appropriate for that engine. This is similar to the way that Perl or Ruby DBI scripts reference only the top-level DBI module; the connect() method provided by the top-level module looks at the DSN and determines which particular lower-level driver to use.

If new PDO() fails, PHP throws an exception. Otherwise, the constructor method returns an object of the PDO class. This object is a database handle that you use for interacting with the database server until you close the connection.

An alternative to putting the connection code directly in your script is to move it into a separate file that you reference from your main script. For example, you could create a file pdo_testdb_connect.php that looks like this:

     # pdo_testdb_connect.php - function for connecting to the "test" database

function testdb_connect ()
{
$dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass");
return ($dbh);
}
?>
Then include the file into your main script and call testdb_connect() to connect and obtain the database handle:
   require_once "pdo_testdb_connect.php";

$dbh = testdb_connect ();
This approach makes it easier to use the same connection parameters in several different scripts without writing the values literally into every script; if you need to change a parameter sometime, just change pdo_testdb_connect.php. Use of a separate file also enables you to move the code that contains the connection parameters outside of the web server's document tree. That has the benefit of preventing it from being displayed literally if the server becomes misconfigured and starts serving PHP scripts as plain text.

Any of the PHP file-inclusion statements can be used, such as include or require, but require_once prevents errors from occurring if any other files that your script uses also reference pdo_testdb_connect.php.

When you're done using the connection, close it by setting the database handle to NULL:

   $dbh = NULL;
After that, $dbh becomes invalid as a database handle and can no longer be used as such.

If you do not close the connection explicitly, PHP does so when the script terminates.

While the database handle is open and you are using it to issue other PDO calls, you should arrange to handle errors if they occur. You can check for an error after each PDO call, or you can cause exceptions to be thrown. The latter approach is simpler because you need not check for errors explicitly; any error raises an exception that terminates your script. If you enable exceptions, you also have the option of catching them yourself instead of allowing them to terminate your script. By doing this, you can substitute your own error messages for the defaults, perform cleanup operations, and so on.

To enable exceptions, set the PDO error mode as follows after connecting:

   $dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That statement is something you could add to the testdb_connect() function if you want the error mode to be set automatically whenever you connect.

For more information on dealing with errors, see "Handling Errors."

Issuing Statements


After obtaining a database handle by calling new PDO(), you can use it to execute SQL statements:

  • For statements that modify rows and produce no result set, pass the statement string to the database handle exec() method, which executes the statement and returns an affected-rows count:
       $count = $dbh->exec ("some SQL statement");
  • For statements that select rows and produce a result set, invoke the database handle query() method, which executes the statement and returns an object of the PDOStatement class:
       $sth = $dbh->query ("some SQL statement");
    This object is a statement handle that provides access to the result set. It enables you to fetch the result set rows and obtain metadata about them, such as the number of columns.
To illustrate how to handle various types of statements, the following discussion shows how to create and populate a table using CREATE TABLE and INSERT (statements that return no result set). Then it uses SELECT to generate a result set.
Issuing Statements That Return No Result Set

The following code uses the database handle exec() method to issue a statement that creates a simple table animal with two columns, name and category:

   $dbh->exec ("CREATE TABLE animal (name CHAR(40), category CHAR(40))");
After the table has been created, it can be populated. The following example invokes the exec() method to issue an INSERT statement that loads a small data set into the animal table:
   $count = $dbh->exec ("INSERT INTO animal (name, category)
VALUES
('snake', 'reptile'),
('frog', 'amphibian'),
('tuna', 'fish'),
('racoon', 'mammal')");
exec() returns a count to indicate how many rows were affected by the statement. For the preceding INSERT statement, the affected-rows count is 4.
Issuing Statements That Return a Result Set

Now that the table exists and contains a few records, SELECT can be used to retrieve rows from it. To issue statements that return a result set, use the database handle query() method:

   $sth = $dbh->query ("SELECT name, category FROM animal");
printf ("Number of columns in result set: %d\n", $sth->columnCount ());
$count = 0;
while ($row = $sth->fetch ())
{
printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
$count++;
}
printf ("Number of rows in result set: %d\n", $count);
A successful query() call returns a PDOStatement statement-handle object that is used for all operations on the result set. Some of the information available from a PDOStatement object includes the row contents and the number of columns in the result set:
  • The fetch() method returns each row in succession, or FALSE when there are no more rows.
  • The columnCount() methods returns the number of columns in the result set.
Note: A statement handle also has a rowCount() method, but it cannot be assumed to reliably return the number of rows in the result set. Instead, fetch the rows and count them, as shown in the preceding example.
Other Ways To Fetch Result Set Rows

fetch() accepts an optional fetch-mode argument indicating what type of value to return. This section describes some common mode values. Assume in each case that the following query has just been issued to produce a result set:

   $sth = $dbh->query ("SELECT name, category FROM animal");
  • PDO::FETCH_NUM
    Return each row of the result set as an array containing elements that correspond to the columns named in the SELECT statement and that are accessed by numeric indices beginning at 0:
       while ($row = $sth->fetch (PDO::FETCH_NUM))
    printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
  • PDO::FETCH_ASSOC
    Return each row as an array containing elements that are accessed by column name:
       while ($row = $sth->fetch (PDO::FETCH_ASSOC))
    printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]);
  • PDO::FETCH_BOTH
    Return each row as an array containing elements that can be accessed either by numeric index or by column name:
       while ($row = $sth->fetch (PDO::FETCH_BOTH))
    {
    printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
    printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]);
    }
  • PDO::FETCH_OBJ
    Return each row as an object. In this case, you access column values as object properties that have the same names as columns in the result set:
       while ($row = $sth->fetch (PDO::FETCH_OBJ))
    printf ("Name: %s, Category: %s\n", $row->name, $row->category);
If you invoke fetch() with no argument, the default fetch mode is PDO::FETCH_BOTH unless you change the default before fetching the rows:
  • The query() method accepts an optional fetch-mode argument following the statement string:
       $sth = $dbh->query ("SELECT name, category FROM animal", PDO::FETCH_OBJ);
    while ($row = $sth->fetch ())
    printf ("Name: %s, Category: %s\n", $row->name, $row->category);
  • Statement handles have a setFetchMode() method to set the mode for subsequent fetch() calls:
       $sth->setFetchMode (PDO::FETCH_OBJ);
    while ($row = $sth->fetch ())
    printf ("Name: %s, Category: %s\n", $row->name, $row->category);
Another way to fetch results is to bind variables to the result set columns with bindColumn(). Then you fetch each row using the PDO::FETCH_BOUND fetch mode. PDO stores the column values in the variables, and fetch() returns TRUE instead of a row value while rows remain in the result set:
   $sth = $dbh->query ("SELECT name, category FROM animal");
$sth->bindColumn (1, $name);
$sth->bindColumn (2, $category);
while ($sth->fetch (PDO::FETCH_BOUND))
printf ("Name: %s, Category: %s\n", $name, $category);

Using Prepared Statements


exec() and query() are PDO object methods: You use them with a database handle and they execute a statement immediately and return its result. It is also possible to prepare a statement for execution without executing it immediately. The prepare() method takes an SQL statement as its argument and returns a PDOStatement statement-handle object. The statement handle has an execute() method that executes the statement:

   $sth = $dbh->prepare ($stmt);
$sth->execute ();
Following execution, other statement-handle methods provide information about the statement result:
  • For a statement that modifies rows, invoke rowCount() to get the rows-affected count:
       $sth = $dbh->prepare ("DELETE FROM animal WHERE category = 'mammal'");
    $sth->execute ();
    printf ("Number of rows affected: %d\n", $sth->rowCount ());
  • For a statement that produces a result set, the fetch() method retrieves them and the columnCount() method indicates how many columns there are. To determine how many rows there are, count them as you fetch them. (As mentioned previously, rowCount() returns a row count, but should be used only for statements that modify rows.)
       $sth = $dbh->prepare ("SELECT name, category FROM animal");
    $sth->execute ();
    printf ("Number of columns in result set: %d\n", $sth->columnCount ());
    $count = 0;
    while ($row = $sth->fetch ())
    {
    printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
    $count++;
    }
    printf ("Number of rows in result set: %d\n", $count);
If you are not sure whether a given SQL statement modifies or returns nows, the statement handle itself enables you to determine the proper mode of processing. See "Determining the Type of a Statement."

As just shown, prepared statements appear to offer no advantage over exec() and query() because using them introduces an extra step into statement processing. But there are indeed some benefits to them:

  • Prepared statements can be parameterized with placeholders that indicate where data values should appear. You can bind specific values to these placeholders and PDO takes care of any quoting or escaping issues for values that contain special characters. "Placeholders and Quoting" discusses these topics further.
  • Separating statement preparation from execution can be more efficient for statements to be executed multiple times because the preparation phase need be done only once. For example, if you need to insert a bunch of rows, you can prepare an INSERT statement once and then execute it repeatedly, binding successive row values to it for each execution.

Placeholders and Quoting


A prepared statement can contain placeholders to indicate where data values should appear. After you prepare the statement, bind specific values to the placeholders (either before or at statement-execution time), and PDO substitutes the values into the statement before sending it to the database server.

PDO supports named and positional placeholders:

  • A named placeholder consists of a name preceded by a colon. After you prepare the statement, use bindValue() to provide a value for each placeholder, and then execute the statement. To insert another row, bind new values to the placeholders and invoke execute() again:
       $sth = $dbh->prepare ("INSERT INTO animal (name, category)
    VALUES (:name, :cat)");
    $sth->bindValue (":name", "ant");
    $sth->bindValue (":cat", "insect");
    $sth->execute ();
    $sth->bindValue (":name", "snail");
    $sth->bindValue (":cat", "gastropod");
    $sth->execute ();
    As an alternative to binding the data values before calling execute(), you can pass the values directly to execute() using an array that associates placeholder names with the values:
       $sth->execute (array (":name" => "black widow", ":cat" => "spider"));
  • Positional placeholders are characters within the statement string. You can bind the values prior to calling execute(), similar to the previous example, or pass an array of values directly to execute():
       $sth = $dbh->prepare ("INSERT INTO animal (name, category)
    VALUES (?, ?)");
    # use bindValue() to bind data values
    $sth->bindValue (1, "ant");
    $sth->bindValue (2, "insect");
    $sth->execute ();
    # pass values directly to execute() as an array
    $sth->execute (array ("snail", "gastropod"));
Positional placeholder numbers begin with 1.

An alternative to bindValue() is bindParam(), which adds a level of indirection to value-binding. Instead of passing a data value as the second argument to bindParam(), pass a variable to associate the variable with the placeholder. To supply a value for the placeholder, assign a value to the variable:

   $sth = $dbh->prepare ("INSERT INTO animal (name, category)
VALUES (?, ?)");
$sth->bindParam (1, $name);
$sth->bindParam (2, $category);
$name = "ant";
$category = "insect";
$sth->execute ();
$name = "snail";
$category = "gastropod";
$sth->execute ();
The preceding examples use INSERT statements, but placeholder techniques are applicable to any type of statement, such as UPDATE or SELECT.

One of the benefits of using placeholders is that PDO handles any quoting or escaping of special characters or NULL values. For example, if you bind the string "a'b'c" to a placeholder, PDO inserts "'a\'b\'c'" into the statement. To bind the SQL NULL value to a placeholder, bind the PHP NULL value. In this case, PDO inserts the word "NULL" into the statement without surrounding quotes. (Were quotes to be added, the value inserted into the statement would be the string "'NULL'", which is incorrect.)

PDO also provides a database handle quote() method to which you can pass a string and receive back a quoted string with special characters escaped. However, I find this method deficient. For example, if you pass it NULL, it returns an empty string, which if inserted into a statement string does not correspond to the SQL NULL value. Use quote() with care if you use it.

Determining the Type of a Statement


When you issue a statement using a database handle, you must know whether the statement modifies rows or produces a result set, so that you can invoke whichever of exec() or query() is appropriate. However, under certain circumstances, you might not know the statement type, such as when you write a script to execute arbitrary statements that it reads from a file. To handle such cases, use prepare() with the database handle to get a statement handle and execute() to execute the statement. Then check the statement's column count:

  • If columnCount() is zero, the statement did not produce a result set. Instead, it modified rows and you can invoke rowCount() to determine the number of affected rows.
  • If columnCount() is greater than zero, the statement produced a result set and you can fetch the rows. To determine how many rows there are, count them as you fetch them.
The following example determines whether a statement modifies rows or produces a result set, and then processes it accordingly:
   $sth = $dbh->prepare ($stmt);
$sth->execute ();
if ($sth->columnCount () == 0)
{
# there is no result set, so the statement modifies rows
printf ("Number of rows affected: %d\n", $sth->rowCount ());
}
else
{
# there is a result set
printf ("Number of columns in result set: %d\n", $sth->columnCount ());
$count = 0;
while ($row = $sth->fetch (PDO::FETCH_NUM))
{
# display column values separated by commas
print (join (", ", $row) . "\n");
$count++;
}
printf ("Number of rows in result set: %d\n", $count);
}

Handling Errors


When you invoke new PDO() to create a database handle, occurrance of an error causes a PDOException to be thrown. If you don't catch the exception, PHP terminates your script. To handle the exception yourself, use a try block to perform the connection attempt and a catch block to catch any error that occurs:

   try
{
$dbh = new PDO("mysql:host=localhost;dbname=test", "testuser", "testpass");
}
catch (PDOException $e)
{
print ("Could not connect to server.\n");
print ("getMessage(): " . $e->getMessage () . "\n");
}
A PDOException is an extension of the PHP Exception class, so it has getCode() and getMessage() methods that return an error code and descriptive message, respectively. (However, I find that getCode() always returns 0 for connection errors and is meaningful only for PDO exceptions that occur after the connection has been established.)

After you successfully obtain a database handle, further PDO calls that use it are handled according to the PDO error mode. There are three modes:

  • PDO::ERRMODE_SILENT
    When an error occurs in silent or warning mode for a given object method, PDO sets up error information that you can access when the method returns. This is the default error mode.
  • PDO::ERRMODE_WARNING
    This is like silent mode but PDO also displays a warning message in addition to setting up error information when an error occurs.
  • PDO::ERRMODE_EXCEPTION
    PDO sets up error information when an error occurs and throws a PDOException.
PDO sets error information for the object to which the error applies, regardless of the error mode. This information is available via the object's errorCode() and errorInfo() methods. errorCode() returns an SQLSTATE value (a five-character string). errorInfo() returns a three-element array containing the SQLSTATE value, and a driver-specific error code and error message. For MySQL, the driver-specific values are a numeric error code and a descriptive error message.

To handle errors in silent mode, you must check the result of each PDO call. The following example shows how to test for errors during an operation that uses a database handle, $dbh, and a statement handle, $sth (you would not necessarily print all the available information as the example does):

   if (!($sth = $dbh->prepare ("INSERT INTO no_such_table")))
{
print ("Could not prepare statement.\n");
print ("errorCode: " . $dbh->errorCode () . "\n");
print ("errorInfo: " . join (", ", $dbh->errorInfo ()) . "\n");
}
else if (!$sth->execute ())
{
print ("Could not execute statement.\n");
print ("errorCode: " . $sth->errorCode () . "\n");
print ("errorInfo: " . join (", ", $sth->errorInfo ()) . "\n");
}
Testing the result of every call can become messy quickly. Another way to deal with failures is to set the error handling mode so that any error raises an exception:
   $dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In this case, you can assume that if you invoke a method and it returns, it succeeded. You can either leave exceptions uncaught or catch and handle them yourself. If you leave them uncaught, exceptions cause PHP to print a backtrace and terminate your script. To catch exceptions, perform PDO operations using a try/catch construct. The try block contains the operations and the catch block handles an execption if one occurs.
   try
{
$sth = $dbh->prepare ("INSERT INTO no_such_table");
$sth->execute ();
}
catch (PDOException $e)
{
print ("The statement failed.\n");
print ("getCode: ". $e->getCode () . "\n");
print ("getMessage: ". $e->getMessage () . "\n");
}
By using try and catch, you can substitute your own error messages if you like, perform cleanup operations, and so on.

As shown in the preceding example, the try block can contain operations on multiple handles. However, if an exception occurs in that case, you won't be able to use the handle-specific errorCode() or errorInfo() methods in the catch block very easily because you won't know which handle caused the error. You'll need to use the information available from the exception methods, as shown.

Using Transactions


In MySQL, some storage engines are transactional, which enables you to perform an operation and then commit it permanently if it succeeded or roll it back to cancel its effects if an error occurred. PDO provides a mechanism for performing transactions that is based on the following database-handle methods:

  • To start a transaction, invoke beginTransaction() to disable autocommit mode so that database changes do not take effect immediately.
  • To commit a successful transaction or roll back an unsuccessful one, invoke commit() or rollback(), respectively.
The easiest way to use these methods is to enable PDO exceptions and use try and catch to handle errors:
   $dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$dbh->beginTransaction (); # start the transaction
# ... perform database operation ...
$dbh->commit (); # success
}
catch (PDOException $e)
{
print ("Transaction failed: " . $e->getMessage () . "\n");
$dbh->rollback (); # failure
}
For additional paranoia, you can place the rollback() call within a nested try/catch construct so that if rollback() itself fails and raises another exception, the script doesn't get terminated.

Resources


Revision History


  • 1.00--Original version.
  • 1.01, 2008-05-07--Removed my mistaken statement that the PDO driver for MySQL requires the mysqli extension. It does not. The driver uses libmysqlclient directly.

Monday, July 26, 2010

Bài 3 Đi lại trong XML bằng XPATH (phần II)

Đi lại trong XML bằng PATH (phần II)

Collections

Cái bộ (Set of) Nodes do XPath trả về được gọi là Collection. Thông thường trong lập trình, từ "Collection" được dùng để nói đến một tập hợp các objects đồng loại. Ta có thể lần lượt đi qua (iterate through) các objects trong một Collection nhưng không được bảo đảm thứ tự của chúng, tức là gặp object nào trước hay object nào sau.

Trái lại, trong chuẩn XPath, khi một Collection được trả về bởi một XPath Query (hỏi), nó giữ nguyên thứ tự các Nodes và cấp bậc của chúng trong tài liệu XML. Tức là nếu XPath trả về một cành các nodes thì trừ những nodes không thỏa điều kiện, các node còn lại vẫn giữ đúng vị trí trên cành.

Vì các Attributes của một Element không có thứ tự, nên chúng có thể nằm lộn xộn trong một Collection.

Indexing trong một Collection

Một Collection của Nodes được xem như một Array. Muốn nói trực tiếp đến một Node trong Collection ta có thể dùng một index trong cặp ngoặc vuông. Node thứ nhất có Index là 1.

Cặp ngoặc vuông ([]) có precedence cao hơn (được tính trước) dấu slash(/) hay hai dấu slash (//). Dưới đây là hai thí dụ:
ExpressionÝ nghĩa
author[1] Element author đầu tiên.
author[firstname][3] Element author thứ ba có mộtElement firstname con.

Mối liên hệ (Axes)

Một location path dùng một Axis để chỉ định mối liên hệ giữa các Nodes được chọn đối với context node. Sau đây là bảng liệt kê đầy đủ các axes:






















































AxesÝ nghĩa
ancestor::
Tổ tiên của context node.

Những tổ tiên của context node gồm có cha, ông nội, ông cố .v.v., do đó ancestor:: axis luôn luôn kể cả root node trừ khi chính context node là root node.

ancestor-or-self::
Chính context node và tổ tiên của nó.

Cái ancestor-or-self:: axis luôn luôn kể cả root node.

attribute::
Các Attributes của context node.

Nếu context node không phải là một Element thì chắc chắn axis sẽ trống rỗng.

child:: Con cái của context node.

Một con là bất cứ node nào nằm ngay dưới context node trong tree. Tuy nhiên, Attribute hay Namespace nodes không được xem là con cái của context node.

descendant::
Con cháu của context node.

Con cháu là con, cháu, chít, .v.v., do đó descendant:: axis không bao giờ chứa Attribute hay Namespace nodes.

following::
Mọi nodes hiện ra sau context node trên tree, không kể con cháu, Attribute nodes, hay Namespace nodes.
following-sibling::
Mọi nodes em (nằm sau) context node.

following-sibling:: axis nói đến chỉ những Nodes con, của cùng một Node cha, nằm trên tree sau context node. Axis không kể các Nodes anh nằm trước context node.

Nếu context node là Attribute hay Namespace thì following-sibling:: axis sẽ trống rỗng.

namespace:: Những Namespace nodes của context node.

Mỗi namespace có một namespace node trong scope (phạm vi hoạt động) của context node.

Nếu context node không phải là một Element thì Axis sẽ trống rỗng.

parent:: Node cha của context node, nếu nó có cha.

Node cha là node nằm ngay phía trên context node trên tree.

preceding::
Mọi nodes hiện ra trước context node trên tree, không kể các nodes tổ tiên, Attribute nodes, hay Namespace nodes.

Một cách để nhận diện preceding:: axis là mọi nodes đã kết thúc hoàn toàn trước khi context node bắt đầu.

preceding-sibling::
Mọi nodes anh (nằm trước) context node.

preceding-sibling:: axis nói đến chỉ những Nodes con, của cùng một Node cha, nằm trên tree trước context node.

Nếu context node là Attribute hay Namespace thì preceding-sibling:: axis sẽ trống rỗng.

self:: Là chính context node.

Sàng lọc (Filters)

Như ta đã thấy ở trên, để giới hạn chỉ lấy ra những Nodes thỏa đáng một điều kiện, ta gắn một Filter (sàng lọc) vào Collection. Filter ấy là một Clause giống giống Clause WHERE trong ngôn ngữ SQL của cơ sở dữ liệu.

Nếu một Collection nằm giữa một filter, nó sẽ cho kết quả TRUE nếu Collection trả về ít nhất một Node và FALSE nếu Collection trống rỗng (empty). Thí dụ expression author/degree có nghĩa rằng hàm biến đổi Collection ra trị số Boolean sẽ có giá trị TRUE nếu hiện hữa một Element author có Element con tên degree.

Filters luôn luôn được tính theo context của nó. Nói một cách khác, cái expression book[author] có nghĩa là cho mỗi Element book tìm thấy, nó sẽ được thử xem có chứa một Element con tên author không. Tương tự như vậy, book[author = 'Brown'] có nghĩa rằng cho mỗi Element book tìm thấy, nó sẽ được thử xem có chứa một Element con tên author với trị số bằng Brown không.

Ta có thể dùng dấu chấm (.) để khám current context node. Thí dụ như, book[. = 'Dreams'] có nghĩa rằng cho mỗi Element book tìm thấy trong current context, nó sẽ được thử xem có trị số bằng Dreams không. Dưới đây là một ít thí dụ:


























ExpressionÝ nghĩa
book[excerpt] Mọi Element book có chứa ít nhất một Element excerpt.
book[excerpt]/title Mọi Element title nằm trong những Element book có chứa ít nhất một Element excerpt.
book[excerpt]/author[degree]
Mọi Element author có chứa ít nhất một Element degree và nằm trong những Elements book có chứa ít nhất một Element excerpt.
book[author/degree] Mọi Element book có chứa ít nhất một Element author với ít nhất một Element degree con.
book[excerpt][title] Mọi Element book có chứa ít nhất một Element excerpt và ít nhất một Element title.

So sánh

Để so sánh hai objects trong XPath ta dùng dấu (=) cho bằng nhau và (!= ) cho không bằng nhau. Mọi Element và Attributes là string, nhưng được Typecast (xem như ) những con số khi đem ra so sánh.


























ExpressionÝ nghĩa
author[lastname = "Smith"]
Mọi Element author có chứa ít nhất một Element lastname với trị số bằng Smith.
author[lastname[1] = "Smith"]
Mọi Element author có Element lastname con đầu tiên với trị số bằng Smith.
author/degree[@from != "Harvard"]
Mọi Element degree, là con một Element author, và có một Attribute from với trị số không phải là "Harvard".
author[lastname = /editor/lastname]
Mọi Element author có chứa một Element lastname bằng với Element lastname là con của root Element editor.
author[. = "John Hamilton"]
Mọi Element author có trị số string là John Hamilton.

Operator Union | (họp lại)

Ngôn ngữ Xpath hỗ trợ Operator Union, giống như Logical OR (hoặc là). Dưới đây là vài thí dụ:






















ExpressionÝ nghĩa
firstname | lastname Mọi Element firstname lastname trong current context.
(bookstore/book | bookstore/magazine) Mọi Element book hay magazine là con một Element bookstore.
book | book/author Mọi Element book hay Element author là con những Elements book.
(book | magazine)/price Mọi Element price là con của Element book hay Element magazine.

Thử loại Node (Node Type Tests)

Để chọn những loại Node khác hơn là Element node, ta dùng Node-Type Test. Mục đích của việc dùng Node-Type test là để chỉ định sự lựa chọn khác thường. Thí dụ như, descendant::text() cho ta mọi text nodes là con cháu của context node, dù rằng loại node chính của con cháu context node là Element. Có 4 loại Node-Type tests như liệt kê dưới đây.



























Node typeTrả vềThí dụ
comment() mọi comment node.following::comment() chọn mọi comment nodes hiện ra sau context node.
node() mọi node.preceding::node() chọn mọi nodes hiện ra trước context node.
processing-instruction() mọi processing instruction node.self::processing instruction() chọn mọi processing instruction nodes trong context node.
text() mọi text node.child::text() chọn mọi text nodes là con của the context node.

Thử Node nhắm vào loại Processing Instruction

Một node test có thể chọn processing instruction thuộc loại nào, tức là chọn mục tiêu (target). Cú pháp của một loại test như thế là:





  processing-instruction("target")

Thí dụ node test sau đây trả về mọi processing instruction nodes có nhắc đến một XSL stylesheet trong tài liệu:





  /child::processing-instruction("xml-stylesheet")


Thêm một số thí dụ Location Path







































































































ExpressionÝ nghĩa
./author Mọi Element author trong current context.

Expresion nầy tương đương với expression trong hàng kế.
author Mọi Element author trong current context.
/bookstore Document (Root) Element tên bookstore của tài liệu nầy.
//author Mọi Element author trong tài liệu.
book[/bookstore/@specialty = @style]
Mọi Element book có Attribute style với value bằng value của Attribute specialty của Document Element bookstore của tài liệu.
author/firstname Mọi Element firstname con của các Elements author.
bookstore//title Mọi Element title một hay nhiều bậc thấp hơn, tức là con cháu của, Element bookstore. Lưu ý là expression nầy khác với expression trong hàng kế.
bookstore/*/title Mọi Element title cháu của các bookstore.
bookstore//book/excerpt//emph Mọi Element emph bất cứ nơi nào dưới excerpt là con của những elements book , bất cứ nơi nào dưới element bookstore.
.//title Mọi Element title một hay nhiều bậc thấp hơn current context node.
author/* Mọi Element là con của các elements con author.
book/*/lastname Mọi Element lastname là cháu của các elements con book.
*/* Mọi Element cháu của current context node.
*[@specialty] Mọi Element con có Attribute specialty.
@style Attribute style của current context node.
price/@exchange Attribute exchange của những Elements price trong current context, tức là những Elements price của current context node.
price/@exchange/total Trả về một node set trống rỗng, vì Attributes không có Element con. Expression nầy được chấp nhận trong văn phạm của XML Path Language, nhưng không thật sự hợp lệ.
book[@style] Mọi Element book có Attribute style trong current context node.
Lưu ý phần nằm trong ngoặc vuông là điều kiện của Element book
book/@style Attribute style của mọi Element booktrong current context node.

Ở đây không có điều kiện như hàng trên. Ta nói đến Attribute hay Element nằm bên phải nhất.
@* Mọi Attributes của current context node.
author[1] Element author thứ nhất trong
current context node.
author[firstname][3] Element author thứ ba có một
Element con firstname.
my:book Element book từ namespace my.
my:* Mọi Element trong namespace my.

Bài 2 Đi lại trong XML bằng XPATH (phần I)

Bài 2 Đi lại trong XML bằng XPATH (phần I)

Chúng ta đã thấy cấu trúc và cú pháp của XML tương đối đơn giãn. XML cho ta một cách chuẩn để trao đổi tin tức giữa các computers. Bước tiếp theo là tìm hiểu cách nào một chương trình chế biến (process) một tài liệu XML


Dĩ nhiên để chế biến một XML chương trình ứng dụng phải có cách đi lại bên trong tài liệu để lấy ra values của các Elements hay Attributes. Do đó người ta thiết kế ra ngôn ngữ XML Path language, mà ta gọi tắt là XPath. XPath đóng một vai trò quan trọng trong công tác trao đổi dữ liệu giữa các computers hay giữa các chương trình ứng dụng vì nó cho phép ta lựa chọn hay sàng lọc ra những tin tức nào mình muốn để trao đổi hay hiển thị.

Nếu khi làm việc với cơ sở dữ liệu ta dùng SQL statement Select .. from TableXYZ  WHERE ... để trích ra một số records từ một table, thì khi làm việc với XML, một table dữ liệu nho nhỏ, XPath cho ta những expressions về criteria (điều kiện) giống giống như clause WHERE trong SQL.


XPath là một chuẩn để process XML, cũng giống như SQL là một chuẩn để làm việc với cơ sở dữ liệu. Tiên phuông trong việc triển khai các chương trình áp dụng XPath là công tác của các công ty phần mềm lớn như Microsoft, Oracle, Sun, IBM, v.v. Sở dĩ ta cần có một chuẩn XPath là vì nó được áp dụng trong nhiều hoàn cảnh, nên cần phải có một lý thuyết rõ ràng, chính xác.

Lý thuyết về XPath hơi khô khan nhưng nó được áp dụng trong mọi kỹ thuật của gia đình XML. Cho nên bạn hãy kiên nhẫn nắm vững những điều căn bản về nó để khi nào gặp chỗ người ta dùng XPath thì mình nhận diện và hiểu được. So với võ thuật, thì XPath trong XML giống như Tấn pháp và cách thở. Tập luyện Tấn pháp thì mõi chân, tập thở thì nhàm chán, nhưng không có hai thứ đó thì ra chiêu không có công lực, chưa đánh đã thua rồi.


Ta sẽ chỉ học những thứ thường dùng trong XPath thôi, nếu bạn muốn có đầy đủ chi tiết về XPath thì có thể tham khão Specification của nó ở http://www.w3c.org/TR/xpath.

 

XML như một cây đối với XPath

XPath cho ta cú pháp để diễn tả cách đi lại trong XML. Ta coi một tài liệu XML như được đại diện bằng một tree (cây) có nhiều nodes. Mỗi Element hay Attribute là một node. Để minh họa ý niệm nầy, bạn hãy quan sát tài liệu đặt hàng (order) XML sau:

<?xml version="1.0"?>
<Order OrderNo="1047">

<OrderDate>2002-03-26</OrderDate>
<Customer>John Costello</Customer>
<Item>
<Product ProductID="1" UnitPrice="70">Chair</Product>

<Quantity>6</Quantity>
</Item>
<Item>
<Product ProductID="2" UnitPrice="250">Desk</Product>

<Quantity>1</Quantity>
</Item>
</Order>

 

Ta có thể biểu diễn XML trên bằng một Tree như dưới đây, trong đó node Element màu nâu, node Attribute màu xanh:

Chỉ định Location Path

Bạn có thể dùng XPath expression để chỉ định Location Path (lối đi đến vị trí) đến node nào hay trích ra (trả về) một hay nhiều nodes thỏa đúng điều kiện yêu cầu. XPath expression có thể là tuyệt đối, tức là lấy node gốc làm chuẩn hay tương đối, tức là khởi đầu từ node vừa mới được chọn. Node ấy được gọi là context node (node vai chính trong tình huống).

Có hai cách viết để diễn tả XPath Location, viết nguyên và viết tắt. Trong cả hai cách ta đều dùng dấu slash (/) để nói đến Document Element, tức là node gốc. Ta có thể đi lại trong các node của Tree giống giống như các node của Windows System Directory mà ta thấy trong Panel bên trái của Window Explorer. Ta cũng sẽ dùng những ký hiệu như slash /, một chấm . và hai chấm .. của Windows System File Folder cho cách viết tắt trong XPath Location để đi xuống các nodes con, cháu, chỉ định context node, hay đi ngược lên các nodes tổ tiên.

 

Location Path tuyệt đối

Chúng ta hãy tìm vài location paths trong cái Tree của tài liệu XML về đặt hàng nói trên. Muốn chọn cái node của Element Order (nó cũng là Root Element) bằng cú pháp nguyên, ta sẽ dùng XPath expression sau đây:

 
  /child::Order 

Dịch ra cú pháp tắt, expression nầy trở nên:

 
  /Order 

Đi ra nhánh của Tree, ta sẽ tìm được node Customer bằng cách dùng XPath expression sau:

 
  /child::Order/child::Customer 

Sau đây là XPath expression viết tắt tương đương:

 
  /Order/Customer 

Nếu bạn muốn lấy ra một node Attribute, bạn phải nói rõ điều nầy bằng cách dùng từ chìa khóa (keyword) attribute trong cách viết nguyên hay dùng character @ trong cú pháp tắt. Do đó để lấy Attribute OrderNo của Element Order, ta sẽ dùng XPath expression sau:

 
  /child::Order/attribute::OrderNo 

Cú pháp tắt cho Attribute OrderNo là:

 
  /Order/@OrderNo 

Để trích ra các nodes con cháu, tức là các nodes nhánh xa hơn, ta dùng keyword descendant trong cú pháp nguyên hay một double slash (//) trong cú pháp tắt. Thí dụ, để lấy ra các nodes Product trong tài liệu, bạn có thể dùng expression location path sau:

 
  /child::Order/descendant::Product 

Cú pháp tắt tương đương là:

 
  /Order//Product 

Bạn cũng có thể dùng wildcards (lá bài Joker) để nói đến những nodes mà tên của chúng không thành vấn đề. Thí dụ, dấu asterisk (*) wildcard chỉ định bất cứ node tên nào. Location path sau đây chọn tất cả các nodes con của Element Order:

 
  /child::Order/child::* 

Cú pháp tắt tương đương là:

 
  /Order/* 

 

Location Path tương đối

Nhiều khi XPath location paths là tương đối với context node, trong trường hợp ấy location path diễn tả cách lấy ra một node hay một số (set of) nodes tương đối với context node. Thí dụ như, nếu Element Item thứ nhất trong order là context node, thì location path tương đối để trích ra Element con Quantity là:

 
  child::Quantity 

Trong cú pháp tắt, location path tương đối là:

 
  Quantity 

Tương tự như vậy, để lấy ra Attribute ProductID của Element con Product, cái location path tương đối là:

 
  child::Product/attribute::ProductID 

Expression ấy dịch ra cú pháp tắt là:

 
  Product/@ProductID 

Để đi ngược lên phía trên của Tree, ta dùng keyword parent (cha). Dạng tắt tương đương của keyword nầy là hai dấu chấm (..). Thí dụ nếu context node là Element OrderDate, thì Attribute OrderNo có thể được lấy ra từ Element Order bằng cách dùng location path tương đối sau:

 
  parent::Order/attribute::OrderNo 

Để ý là cú pháp nầy chỉ trả về một trị số khi node cha tên Order. Nếu muốn lấy ra Attribute OrderNo từ node cha không cần biết nó tên gì bạn phải dùng expression sau:

 
  parent::*/attribute::OrderNo 

Viết theo kiểu tắt đơn giản hơn vì bạn không cần phải cung cấp tên của node cha. Bạn có thể nói đến node cha bằng cách dùng hai dấu chấm (..) như sau:

 
  ../@OrderNo 

Ngoài ra, bạn có thể nói đến chính context node bằng cách dùng hoặc keyword self hoặc một dấu chấm (.). Điều nầy rất tiện trong vài trường hợp, nhất là khi bạn muốn biết current context node là node nào.

Dùng điều kiện trong Location Path

Bạn có thể giới hạn số nodes lấy về bằng cách gắn thêm điều kiện sàng lọc vào location path. Cái điều kiện giới hạn một hay nhiều nodes được tháp vào expression bên trong một cặp ngoặc vuông ([]). Thí dụ, để lấy ra mọi Element Product có Attribute UnitPrice lớn hơn 70, bạn có thể dùng XPath expression sau đây:

 
  /child::Order/child::Item/child::Product[attribute::UnitPrice>70] 

Trong cú pháp tắt, nó là:

 
  /Order/Item/Product[@UnitPrice>70] 

Trong expression của điều kiện bạn cũng có thể dùng Xpath tương đối , do đó trong expression điều kiện bạn có thể dùng bất cứ node nào trong thứ bậc. Thí dụ sau đây lấy về những nodes Item có Element con Product với Attibute ProductID trị số bằng 1:

 
  /child::Order/child::Item[child::Product/attribute::ProductID=1] 

Dịch ra cú pháp tắt, ta có:

 
  /Order/Item[Product/@ProductID=1] 

Bài 1 Tìm hiểu cấu trúc và cú pháp của XML

Bài 1 Tìm hiểu cấu trúc và cú pháp của XML

Để thấy ảnh hưởng rộng lớn của XML trong ngành Công Nghệ Thông Tin cận đại bạn chỉ cần để ý rằng XML là lý do của sự hiện hữu (raison d'être) của Microsoft .Net. Từ WindowsXP trở đi, bên trong đầy dẫy XML. Microsoft đã đầu tư hơn 3 tỷ đô la Mỹ vào kỹ thuật nầy, và trong tương lai gần đây tất cả phần mềm của Microsoft nếu không dọn nhà (được ported) qua .NET thì ít nhất cũng được .NET Enabled (dùng cho .NET được). Đi song song với .NET là SQLServer 2000, một cơ sở dữ liệu hổ trợ XML hoàn toàn.

Có lẽ bạn đã nghe qua Web Services. Đó là những dịch vụ trên Web ta có thể dùng on-demand , tức là khi nào cần cho chương trình của mình, bằng cách gọi nó theo phương pháp giống giống như gọi một Hàm (Function). Web Services được triển khai dựa vào XML và Http, chuẩn dùng để gởi các trang Web.

Điểm quan trọng của kỹ thuật XML là nó không thuộc riêng về một công ty nào, nhưng là một tiêu chuẩn được mọi người công nhận vì được soạn ra bởi World Wide Web Consortium - W3C (một ban soạn thão với sự hiện diện của tất cả các dân có máu mặt trên giang hồ Tin học) và những ai muốn đóng góp bằng cách trao đổi qua Email. Bản thân của XML tuy không có gì khó hiểu, nhưng các công cụ chuẩn được định ra để làm việc với XML như Document Object Model - DOM, XPath, XSL, v.v.. thì rất hữu hiệu, và chính các chuẩn nầy được phát triển không ngừng.

Microsoft committed (nhất quyết dấn thân) vào XML ngay từ đầu. Chẳng những có đại diện để làm việc thường trực trong W3C mà còn tích cực đóng góp bằng cách gởi những đề nghị. Vị trí của Microsoft về XML là khi tiêu chuẩn chưa được hoàn thành thì các sản phẩm của Microsoft tuân thủ (comply) những gì có vẽ được đa số công nhận và khi tiêu chuẩn hoàn thành thì tuân thủ hoàn toàn.

Cái công cụ XML sáng giá nhất của Microsoft là ActiveX MSXML. Nó được dùng trong Visual Basic 6, ASP (Active Server Pages) của IIS và Internet Explorer từ version 5.5. Hiện nay MSXML đã có version 4.0. MSXML parse (đọc và phân tích) và validate (kiểm tra sự hợp lệ) XML file để cho ta DOM, một tree của các Nodes đại diện các thành phần bên trong XML. MSXML cũng giúp ta dựa vào một XSL file để transform (biến thể) một XML file thành một trang Web (HTML) hay một XML khác.

 

XML là gì?

Một chút lịch sử

Như tất cả chúng ta đều biết, XML là viết tắt cho chữ eXtensible Markup Language - nhưng Markup Language (ngôn ngữ đánh dấu) là gì?

Trong ngành ấn loát, để chỉ thị cho thợ sắp chữ về cách in một bài vỡ, tác giả hay chủ bút thường vẽ các vòng tròn trong bản thão và chú thích bằng một ngôn ngữ đánh dấu tương tự như tốc ký. Ngôn ngữ ấy được gọi là Markup Language.

XML là một ngôn ngữ đánh dấu tương đối mới vì nó là một subset (một phần nhỏ hơn) của và đến từ (derived from) một ngôn ngữ đánh dấu già dặn tên là Standard Generalized Markup Language (SGML). Ngôn ngữ HTML cũng dựa vào SGML, thật ra nó là một áp dụng của SGML.

SGML được phát minh bởi Ed Mosher, Ray Lorie và Charles F. Goldfarb của nhóm IBM research vào năm 1969, khi con người đặt chân lên mặt trăng. Lúc đầu nó có tên là Generalized Markup Language (GML), và được thiết kế để dùng làm meta-language, một ngôn ngữ được dùng để diễn tả các ngôn ngữ khác - văn phạm, ngữ vựng của chúng ,.v.v.. Năm 1986, SGML được cơ quan ISO (International Standard Organisation) thu nhận (adopted) làm tiêu chuẩn để lưu trữ và trao đổi dữ liệu. Khi Tim Berners-Lee triển khai HyperText Markup Language - HTML để dùng cho các trang Web hồi đầu thập niên 1990, ông ta cứ nhắc nhở rằng HTML là một áp dụng của SGML.

Vì SGML rất rắc rối, và HTML có nhiều giới hạn nên năm 1996 tổ chức W3C thiết kế XML. XML version 1.0 được định nghĩa trong hồ sơ February 1998 W3C Recommendation, giống như một Internet Request for Comments (RFC), là một "tiêu chuẩn".

Từ HTML đến XML

Trong một trang Web, ngôn ngữ đánh dấu HTML dùng các cặp Tags để đánh dấu vị trí đầu và cuối của các mảnh dữ liệu để giúp chương trình trình duyệt (browser) parse (ngắt khúc để phân tích) trang Web và hiển thị các phần theo ý người thiết kế trang Web. Thí dụ như một câu HTML dưới đây:
<P align="center">Chào mừng bạn đến thăm 
<STRONG>Vovisoft</STRONG>Web site </
P>
Câu code HTML trên có chứa hai markup Tags, <P><STRONG>. Mỗi cặp Tags gói dữ liệu nó đánh dấu giữa opening Tagclosing Tag. Hai closing Tags ở đây là </P></STRONG>. Tất cả những gì nằm bên trong một cặp Tags được gọi là Element. Để nói thêm đặc tính của một Element, ta có thể nhét Attribute như align trong opening Tag của Element ấy dưới dạng AttributeName="value", thí dụ như align="center".


Vì Tags trong HTML được dùng để format (trình bày) tài liệu nên browser cần biết ý nghĩa của mỗi Tag. Một browser hay HTML parser sẽ thu thập các chỉ thị sau từ câu HTML trên:
  1. Bắt đầu một Paragraph mới và đặt Text ở giữa trang (<P align="center">).
  2. Hiển thị câu Chào mừng bạn đến thăm
  3. Hiển thị chữ Vovisoft cách mạnh mẽ (<STRONG>Vovisoft</STRONG>).
  4. Hiển thị câu Web site
  5. Gặp điểm cuối của Paragraph (</P>)
Để xử lý đoạn code HTML trên, chẳng những browser cần phải xác định vị trí các Tags mà còn phải hiểu ý nghĩa của mỗi Tag. Vì mỗi Tag có ý ngĩa riêng của nó, thí dụ P cho Paragraph, STRONG để nhấn mạnh, thí dụ như dùng chữ đậm (Bold).

Giống như HTML, XML đến từ SGML. Nó cũng dùng Tags để encode data. Điểm khác biệt chánh giữa HTML và XML là trong khi các Tags của HTML chứa ý nghĩa về formatting (cách trình bày) các dữ liệu, thì các Tags của XML chứa ý nghĩa về cấu trúc của các dữ liệu. Thí dụ như một tài liệu đặt hàng (order) XML dưới đây:
<Order OrderNo="1023">
<OrderDate>2002-3-27</OrderDate>
<Customer>Peter Collingwood</Customer>
<Item>
<ProductID>1</ProductID>
<Quantity>5</Quantity>
</Item>
<Item>
<ProductID>4</ProductID>
<Quantity>3</Quantity>
</Item> </
Order>
Tài liệu nầy chỉ chứa dữ liệu, không nhắc nhở gì đến cách trình bày. Điều nầy có nghĩa là một XML parser (chương trình ngắt khúc và phân tích) không cần phải hiểu ý nghĩa cũa các Tags. Nó chỉ cần tìm các Tags và xác định rằng đây là một tài liệu XML hợp lệ. Vì browser không cần phải hiểu ý nghĩa của các Tags, nên ta có thể dùng Tag nào cũng được. Đó là lý do người ta dùng chữ eXtensible (mở rộng thêm được), nhưng khi dùng chữ để viết tắt thì lại chọn X thay vì e, có lẽ vì X nghe có vẽ kỳ bí, hấp dẫn hơn.

Chúng ta hãy quan sát kỹ hơn cấu trúc của một XML. Trước hết, Element Order có Attribute OrderNo với value 1023. Bên trong Element Order có:
  • Một Child (con) Element OrderDate với value 2002-3-27
  • Một Child Element Customer với value Peter Collingwood.
  • Hai Child Elements Item, mỗi Element Item lại chứa một Child Element ProductID và một Child Element Quantity.
Đôi khi ta để một Element với tên đàng hoàng, nhưng không chứa một value, lý do là ta muốn dùng nó như một Element Nhiệm ý (Optional), có cũng được, không có cũng không sao. Cách tự nhiên nhất là gắn cái closing Tag ngay sau opening Tag. Thí dụ như Empty (trống rỗng) Element MiddleInitial trong Element customer dưới đây:
<Customer>
<FirstName>Stephen</ FirstName>
<MiddleInitial></MiddleInitial> <LastName>King</LastName>
</Customer>
Có một cách khác để biểu diễn Empty Element là bỏ closing Tag và thêm một dấu "/" (slash) ở cuối openning Tag. Ta có thể viết lại thí dụ customer như sau:
<Customer>
<FirstName>Stephen</FirstName>
<MiddleInitial/>
<LastName>King</LastName>
</Customer>
Dĩ nhiên Empty Element cũng có thể có Attribute như Element PhoneNumber thứ nhì dưới đây:

<Customer>
<FirstName>Stephen</FirstName>
<MiddleInitial></MiddleInitial>
<LastName>King</LastName>
<PhoneNumber Location="Home">9847 2635</PhoneNumber>
<PhoneNumber Location="Work"></PhoneNumber>
</Customer>

Biểu diễn Data trong XML

Một tài liệu XML phải well-formedvalid. Mặc dầu hai từ nầy nghe tờ tợ, nhưng chúng có ý nghĩa khác nhau. Một XML well-formed là một XML thích hợp cho parser chế biến. Tức là XML tuân thủ các luật lệ về Tag, Element, Attribute , value .v.v.. chứa bên trong để parser có thể nhận diện và phân biệt mọi thứ.

Để ý là một XML well-formed chưa chắc chứa đựng những dữ liệu hữu dụng trong công việc làm ăn. Là well-formed chỉ có nghĩa là XML có cấu trúc đúng. Để hữu dụng cho công việc làm ăn, XML chẳng những well-formed mà còn cần phải valid. Một tài liệu XML valid khi nó chứa những data cần có trong loại tài liệu loại hay class ấy. Thí dụ một XML đặt hàng có thể bị đòi hỏi phải có một Attribute OrderNo và một Child Element Orderdate. Parser validate một XML bằng cách kiểm tra data trong XML xem có đúng như định nghĩa trong một Specification về loại tài liệu XML ấy. Specification nầy có thể là một Document Type Definition (DTD) hay một Schema.

Chốc nữa ta sẽ nói đến valid, bây giờ hãy bàn về well-formed.

Tạo một tài liệu XML well-formed

Để well-formed, một tài liệu XML phải theo đúng các luật sau đây:
  1. Phải có một root (gốc) Element duy nhất, gọi là Document Element, nó chứa tất cả các Elements khác trong tài liệu.
  2. Mỗi opening Tag phải có một closing Tag giống như nó.
  3. Tags trong XML thì case sensitive, tức là opening Tag và closing Tag phải được đánh vần y như nhau, chữ hoa hay chữ thường.
  4. Mỗi Child Element phải nằm trọn bên trong Element cha của nó.
  5. Attribute value trong XML phải được gói giữa một cặp ngoặc kép hay một cặp apostrophe.
Luật thứ nhất đòi hỏi một root Element duy nhất, nên tài liệu dưới đây không well-formed vì nó không có một top level Element:
<Product ProductID="1">Chair</Product>
<Product ProductID="2">Desk</Product>
Một tài liệu XML không có root Element được gọi là một XML fragment (mảnh). Để làm cho nó well-formed ta cần phải thêm một root Element như dưới đây:

<Catalog>
<Product ProductID="1">Chair</Product>
<Product ProductID="2">Desk</Product>
</Catalog>
Luật thứ hai nói rằng mỗi opening Tag phải có một closing Tag giống như nó. Tức là mỗi Tag mở ra phải được đóng lại. Empty Element viết cách gọn như <MiddleInitial/> được gọi là có Tag tự đóng lại. Các Tags khác phải có closing Tag. Cái XML dưới đây không well-formed vì nó có chứa một một Tag <Item> thiếu closing Tag </Item>:
<Order>
<OrderDate>2002-6-14</OrderDate>
<Customer>Helen Mooney</Customer>
<Item>
<ProductID>2</ProductID>
<Quantity>1</Quantity>
<Item>
<ProductID>4</ProductID>
<Quantity>3</Quantity>
</Item>
</Order>

Để làm cho nó well-formed ta phải thêm cái closing tag cho Element Item thứ nhất:

<Order>
<OrderDate>2002-6-14</OrderDate>
<Customer>Helen Mooney</Customer>
<Item>
<ProductID>2</ProductID>
<Quantity>1</Quantity>
</Item>
<Item>
<ProductID>4</ProductID>
<Quantity>3</Quantity>
</Item>
</Order>

Luật thứ ba nói là tên Tag thì case sensitive, tức là closing Tag phải đánh vần y hệt như opening Tag, phân biệt chữ hoa, chữ thường. Như thế <order> khác với <Order>, ta không thể dùng Tag </Order> để đóng Tag <order>. Cái XML dưới đây không well-formed vì opening Tag và closing Tags của Element OrderDate không đánh vần giống nhau:
<Order>
<OrderDate>2001-01-01</Orderdate>
<Customer>Graeme Malcolm</Customer>
</Order>
Muốn làm cho nó well formed, ta phải sửa chữ d thành chữ hoa (uppercase) D như sau:
<Order>
<OrderDate>2001-01-01</OrderDate>
<Customer>Graeme Malcolm</Customer>
</Order>
Luật thứ tư nói mỗi Child Element phải nằm trọn bên trong Element cha của nó, tức là không thể bắt đầu một Element mới khi Element nầy chưa chấm dứt. Thí dụ như tài liệu XML dưới đây không well-formed vì closing Tag của Category hiện ra trước closing Tag của Product.
<Catalog>
<Category CategoryName="Beverages">
<Product ProductID="1">
Coca-Cola
</Category>
</Product>
</Catalog>
Muốn sửa cho nó well-formed ta cần phải đóng Tag Product trước như dưới đây:
<Catalog>
<Category CategoryName="Beverages">
<Product ProductID="1">
Coca-Cola
</Product>
</Category>
</Catalog>
Luật cuối cùng về tài liệu XML well-formed đòi hỏi value của Attribute phải được gói trong một cặp apostrophe hay ngoặc kép. Tài liệu dưới đây không well-form vì các Attribute values không được ngoặc đàng hoàng, số 1 không có dấu ngoặc, số 2 có một cái apostrophe, một cái ngoặc kép:

<Catalog>
<Product ProductID=1>Chair</Product>
<Product ProductID='2">Desk</Product>
</Catalog>

Processing Instructions và Comments

Ngoài các dữ liệu cần thiết cho công việc làm ăn, một tài liệu XML cũng có chứa các Processing Instructions (chỉ thị về cách chế biến) cho parser và Comments (ghi chú) cho người đọc.

Processing Instruction nằm trong cặp Tags <??>. Thông thường nó cho biết version của XML Specification mà parser cần làm theo. Có khi nó cũng cho biết data trong XML dùng encoding nào, thí dụ như uft-8. Còn một Attribute nữa là standalone. standalone cho parser biết là tài liệu XML có thể được validated một mình, không cần đến một DTD hay Schema.

Mặc dầu một tài liệu XML well-formed không cần có một Processing Instruction, nhưng thông thường ta để một Processing Instruction ở đàng đầu tài liệu, phần ấy được gọi là prologue (giáo đầu). Dưới đây là một thí dụ có Processing Instruction trong prologue của một tài liệu XML:

<?xml version="1.0" encoding="utf-8"  standalone="yes"?>
<Order>
<OrderDate>2002-6-14</OrderDate>
<Customer>Helen Mooney</Customer>
<Item>
<ProductID>1</ProductID>
<Quantity>2</Quantity>
</Item>
<Item>
<ProductID>4</ProductID>
<Quantity>1</Quantity>
</Item>
</Order>

Có một loại Processing Instruction khác cũng rất thông dụng là cho biết tên của stylesheet của XML nầy, thí dụ như:
<?xml-stylesheet type="text/xsl" href="order.xsl"?> 
Ở đây ta cho XML stylesheet parser biết rằng stylesheet thuộc loại text/xsl và nó được chứa trong file tên order.xsl. Bạn cũng có thể cho thêm Comment bằng cách dùng cặp Tags <!----> như sau:

<?xml version="1.0" encoding="utf-8"  standalone="yes"?>
<!-- Below are details of a purchase order. -->
<Order>
<OrderDate>2002-6-14</OrderDate>
<Customer>Helen Mooney</Customer>
<Item>
<ProductID>1</ProductID>
<Quantity>2</Quantity>
</Item>
<Item>
<ProductID>4</ProductID>
<Quantity>1</Quantity>
</Item>
</Order>

Namespaces

Có một ý niệm rất quan trọng trong XML là Namespace. Nó cho ta cách cùng một tên của Element để nói đến hai thứ dữ liệu khác nhau trong cùng một tài liệu XML. Giống như có hai học sinh trùng tên Tuấn trong lớp học, ta phải dùng thêm họ của chúng để phân biệt, ta gọi Tuấn Trần hay Tuấn Lê. Thí dụ như có một order được người ta đặt trong tiệm sách như sau:

<?xml version="1.0"?>
<BookOrder OrderNo="1234">
<OrderDate>2001-01-01</OrderDate>
<Customer>
<Title>Mr.</Title>
<FirstName>Graeme</FirstName>
<LastName>Malcolm</LastName>
</Customer>
<Book>
<Title>Treasure Island</Title>
<Author>Robert Louis Stevenson</Author>
</Book>
</BookOrder>
Khi quan sát kỹ, ta thấy có thể có sự nhầm lẫn về cách dùng Element Title. Trong tài liệu có hai loại Title, một cái dùng cho khách hàng Customer nói đến danh hiệu Mr., Mrs., Dr., còn cái kia để nói đến đề tựa của một quyển sách Book.

Để tránh sự lầm lẫn, bạn có thể dùng Namespace để nói rõ tên Element ấy thuộc về giòng họ nào. Giòng họ ấy là một Universal Resource Identifier (URI). Một URI có thể là một URL hay một chỗ nào định nghĩa tính cách độc đáo của nó. Một namespace cũng không cần phải nói đến một địa chỉ Internet, nó chỉ cần phải là có một, không hai.

Bạn có thể khai báo namespaces trong một Element bằng cách dùng Attribute xmlns (ns trong chữ xmlns là viết tắt cho namespace) bạn cũng có thể khai báo một default namespace để áp dụng cho những gì nằm bên trong một Element, nơi bạn khai báo namespace. Thí dụ cái tài liệu đặt hàng có thể được viết lại như sau:

<?xml version="1.0"?>
<BookOrder OrderNo="1234">
<OrderDate>2001-01-01</OrderDate>
<Customer xmlns="http://www.northwindtraders.com/customer">
<Title>Mr.</Title>
<FirstName>Graeme</FirstName>
<LastName>Malcolm</LastName>
</Customer>
<Book xmlns="http://www.northwindtraders.com/book">
<Title>Treasure Island</Title>
<Author>Robert Louis Stevenson</Author>
</Book>
</BookOrder>

Ta đã tránh được sự nhầm lẫn vì bên trong Customer thì dùng namespace http://www.northwindtraders.com/customer và bên trong Book thì dùng namespace http://www.northwindtraders.com/book.

Tuy nhiên, ta sẽ giải quyết làm sao nếu trong order có nhiều customer và nhiều book. Nếu cứ thay đổi namespace hoài trong tài liệu thì chóng mặt chết. Một cách giải quyết là khai báo chữ viết tắt cho các namespaces ngay ở đầu tài liệu, trong root Element (tức là Document Element). Sau đó bên trong tài liệu ta sẽ prefix các Element cần xác nhận namespace bằng chữ viết tắt của namespace nó. Thí dụ như sau:

<?xml version="1.0"?>
<BookOrder xmlns="http://www.northwindtraders.com/order"
xmlns:cust="http://www.northwindtraders.com/customer"
xmlns:book="http://www.northwindtraders.com/book" OrderNo="1234"
>
<OrderDate>2001-01-01</OrderDate>
<cust:Customer>
<cust:Title>Mr.</cust:Title>
<cust:FirstName>Graeme</cust:FirstName>
<cust:LastName>Malcolm</cust:LastName>
</cust:Customer>
<book:Book>
<book:Title>Treasure Island</book:Title>
<book:Author>Robert Louis Stevenson</book:Author>
</book:Book>
</BookOrder>
Trong tài liệu XML trên ta dùng 3 namespaces: một default namespace tên http://www.northwindtraders.com/order, namespace http://www.northwindtraders.com/customer (viết tắt là cust) và namespace http://www.northwindtraders.com/book (viết tắt là book). Các Elements và Attributes không có prefix (tức là không có chữ tắt đứng trước) như BookOrder, OrderNo, và OrderDate, được coi như thuộc về default namespace. Để đánh dấu một Element hay Attribute không thuộc về default namespace, một chữ tắt, đại diện namespace sẽ được gắn làm prefix cho tên Element hay Attribute. Thí dụ như cust:LastName, book:Title.

CDATA

CDATA là khúc dữ liệu trong tài liệu XML nằm giữa <![CDATA[]]>. Data nằm bên trong những CDATA được cho thông qua parser y nguyên, không bị sửa đổi. Điểm nầy rất quan trọng khi bạn muốn cho vào những dữ liệu có chứa những text được xem như markup. Bạn có thể đặt những thí dụ cho XML trong những CDATA và chúng sẽ được parser bỏ qua. Khi dùng XSL stylesheets để transform một XML file thành HTML, có bất cứ scripting nào bạn cũng phải đặt trong những CDATA. Dưới đây là các thí dụ dùng CDATA:
<![CDATA[...place your data here...]]>

<SCRIPT>
  <![CDATA[
      function warning()
    {
        alert("Watch out!");
    }
   ]]>
</SCRIPT>

Entity References

Entity nói đến cách viết một số dấu đặc biệt đã được định nghĩa trước trong XML. Có 5 entities dưới đây:

Entity

Description

&apos; dấu apostrophe
&amp; dấu ampersand
&gt; dấu lớn hơn
&lt; dấu nhỏ hơn
&quot; dấu ngoặc kép
Trong bài tới ta sẽ học về cách process (chế biến) một tài liệu XML