Using MD5 to Encrypt Passwords in a Database, Part 2

Using MD5 to Encrypt Passwords in a Database, Part 2

In Part 1 we looked briefly at the motivation behind using encrypted passwords and examined different classes of encryption algorithms, including MD5. In this part we'll examine how to implement encrypted passwords using MD5!

Using MD5 To Store Encrypted Passwords
Earlier I mentioned that most sites that support user accounts do so by using a database table named something like
UserAccount, with fields like UserName and Password. In the case where the password is saved as plain-text, both the UserName and Password fields are of type varchar. However, if we plan on using encrypted passwords we need to change the type of the Password field from a varchar to a binary type of length 16. This change is needed because the encrypted version of the user's password will be a 16-element array of bytes.

Now, whenever a user creates an account, we need to be certain to store the encrypted form of the password they selected into the database. The following ASP.NET code provides a sample Web page for creating a user account. It prompts the user for their username and password and stores these values into a UserAccount database table. However, instead of storing the password as-entered by the user, it first encrypts it using the MD5 code we examined earlier, and then saves to the database this encrypted version.

<%@ Import Namespace="System.Security.Cryptography" %>

<%@ Import Namespace="System.Text" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server" language="VB">

Sub CreateAccount(sender as Object, e as EventArgs)

'1. Create a connection

Const strConnString as String = "connection string"

Dim objConn as New SqlConnection(strConnString)

'2. Create a command object for the query

Dim strSQL as String = _

"INSERT INTO UserAccount(Username,Password) " & _

"VALUES(@Username, @Password)"

Dim objCmd as New SqlCommand(strSQL, objConn)

'3. Create parameters

Dim paramUsername as SqlParameter

paramUsername = New SqlParameter("@Username", SqlDbType.VarChar, 25)

paramUsername.Value = txtUsername.Text


'Encrypt the password

Dim md5Hasher as New MD5CryptoServiceProvider()

Dim hashedBytes as Byte()

Dim encoder as New UTF8Encoding()

hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPwd.Text))

Dim paramPwd as SqlParameter

paramPwd = New SqlParameter("@Password", SqlDbType.Binary, 16)

paramPwd.Value = hashedBytes


'Insert the records into the database




'Redirect user to confirmation page...

End Sub


<form runat="server">

<h1>Create an Account</h1>

Username: <asp:TextBox runat="server" id="txtUsername" />

<br />Password:

<asp:TextBox runat="server" id="txtPwd" TextMode="Password" />

<p><asp:Button runat="server" Text="Create Account"

OnClick="CreateAccount" /></p>


Note that the above code sample imports a number of namespaces. These namespaces are imported to save typing (for example, if the System.Security.Cryptography namespace were not imported, when referring to the MD5CryptoServiceProvider class, the code would have to appear as: System.Security.Cryptography.MD5CryptoServiceProvider). The code provides the user with two TextBoxes, one for the username and one for the password. Once the user has supplied these values and clicked the "Create Account" button, the CreateAccount event handler will be executed, and the database table UserAccounts will have a new row added representing the new user.

The screenshot to the right shows the values in the UserAccounts table after some users have been created. Note that the password contains a 16-element binary array, representing the encrypted password. Clearly if someone were to be able to examine the UserAccounts table they could not deduce the plain-text password of any of the users.

Using MD5 To Authenticate a User
Since we are storing the passwords in encrypted form, and since, by the nature of a one-way encryption algorithm it is impossible to retrace from the encrypted form to the plain-text form, you may be wondering how in the world we'll authenticate a user. That is, when a user wants to login and supplies her username and password, how will we know if she provided the correct password?

Recall one of the properties of MD5 - that for any plain-text input the encrypted version of the input will be the same, always. That is, if we use MD5 to generate an encrypted form of the plain-text string "my password", the encrypted version of this will be the same today and forever more. Therefore, to authenticate a user we can simply take the password they provide, encrypt it using MD5, and then see if that encrypted form exists in the database (along with their username). The following code performs this check, logging in a user:

<%@ Import Namespace="System.Security.Cryptography" %>

<%@ Import Namespace="System.Text" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server" language="VB">

Sub Login(sender as Object, e as EventArgs)

'1. Create a connection

Const strConnString as String = "connection string"

Dim objConn as New SqlConnection(strConnString)

'2. Create a command object for the query

Dim strSQL as String = "SELECT COUNT(*) FROM UserAccount " & _

"WHERE Username=@Username AND Password=@Password"

Dim objCmd as New SqlCommand(strSQL, objConn)

'3. Create parameters

Dim paramUsername as SqlParameter

paramUsername = New SqlParameter("@Username", SqlDbType.VarChar, 25)

paramUsername.Value = txtUsername.Text


'Encrypt the password

Dim md5Hasher as New MD5CryptoServiceProvider()

Dim hashedDataBytes as Byte()

Dim encoder as New UTF8Encoding()

hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPwd.Text))

Dim paramPwd as SqlParameter

paramPwd = New SqlParameter("@Password", SqlDbType.Binary, 16)

paramPwd.Value = hashedDataBytes


'Insert the records into the database


Dim iResults as Integer = objCmd.ExecuteScalar()


If iResults = 1 then

'The user was found in the DB


'The user was not found in the DB

End If

End Sub


<form runat="server">


Username: <asp:TextBox runat="server" id="txtUsername" />

<br />Password:

<asp:TextBox runat="server" id="txtPwd" TextMode="Password" />

<p><asp:Button runat="server" Text="Login" OnClick="Login" />


Limitations of Storing Encrypted Passwords in the Database
Before you decide whether or not to employ encrypted passwords in your next project, there are a few limitations to be aware of. First, realize that since the passwords are encrypted, there is no way to determine what a user's password is! While this is exactly what we were after by encrypting passwords in the first place, it means that you cannot provide users with a "Click here to have your password emailed to you" feature. Rather, if the user forgets his password he'll have to have his password reset to some random password, and then be emailed that new, random password. Essentially we cannot email the user his forgotten password because there's no way to determine what, exactly, his password is!

Also, converting from a plain-text password system to an encrypted system is possible, but can be a bit difficult. Essentially, you need to create a new table with the Password field being of type binary and of length 16. Next, you have to use an ASP.NET Web page or a .NET program to read the contents of the existing user database, and for each record, add it to the new table making sure to encrypt the user's password using MD5. Be careful not to delete the old user's account information until you're certain that you copied over their information correctly!

Important Security Note!

The hashing technique discussed in this article is susceptible to dictionary attacks. A much more secure approach is to salt the hash in some manner. For a thorough discussion on what salting is and why it's an important precaution, be sure to read: Could you Pass the Salt? Improving the Security in Encrypting Passwords using MD5.

In this article we looked at how to use MD5 to provide encrypted passwords in a database. The .NET Framework contains an
MD5CryptoServiceProvider class that provides MD5 encryption functionality. Recall that MD5 is a one-way encrypting algorithm, meaning that it can be used to encrypt a plain-text string to an encrypted form, but not back the other way around. Encrypted passwords make sense for applications where one can do much damage by discovering a user's password, but due to their limitations, may not be suitable for less sensitive applications.

Using MD5 to Encrypt Passwords in a Database Part 1

Using MD5 to Encrypt Passwords in a Database

There are, as you know, a plethora of Web sites on the Internet that allow for, if not require, some sort of user account. For example, on, in order to post a message one must create a user account, which includes information like username, email address, and password. To buy a book from you must create an account, which includes your name, an email address, a password, a shipping address, and so on. Note that each of these user accounts requires, among other things, a username and password pair, which are used to authenticate a user.

If you've designed a site that required allowing user accounts you likely implemented the user account by creating a database table named something like UserAccount, with fields like UserName and Password. This table would contain a row for each user; when a user wished to log on, they'd submit their username and password, which would be used to query the UserAccount to see if there was a row whose UserName and Password fields matched the user-supplied username and password.

While this approach is pretty typical one of its downsides is that each user's password is stored in an unencrypted form in the database. That means that if someone compromises your database they have access to the passwords for every user. In this article we'll look at how to use MD5 to encrypt your passwords so that not even the database administrator can determine a user's password.

Is Your Data Safe?
Realize that the data in your database is not safe. Imagine that you host a database at a respectable Web hosting company that keeps the database patches up-to-date and has never had someone gain unauthorized access to the database before. While you may think that in such a situation your data is private from all others, understand that any database administrator who works at the Web hosting company will be able to view your data at will.

Before deciding to implement a password encryption scheme, as will be described in this article, one must ask themselves not how safe is their data, but how sensitive it is. That is, assume that others will see your information. If it is vitally important that this not incur, such a password encrypting scheme is ideal. For example, a financial institution should use encrypted passwords, so that there is not a risk of someone issuing an unauthorized transaction in your name. However, you may decide it not worth the hassle to implement password encryption for, say, a messageboard site, figuring that even if someone does obtain the password for every user, you can just reset everyone's password to some random value and have each person login with their new password and change it. In the former case much irreparable harm can be done; in the latter case, it may be an annoyance to deal with, but in the end does it really matter if your messageboard Web site incurs a security breach?

MD5 Encryption - A Brief Summary
There are two general classes of encryption: one-way encryption and two-way encryption. Two-way encryption is the most common form of encryption. It takes a plain-text input and encrypts it into some encrypted text. Then, at some later point in time, this encrypted text can be decrypted, which results in the plain-text that was originally encrypted. Two-way encryption is useful for private communications. For example, imagine that you wanted to send an eCommerce Web site your credit card number to make a purchase. You wouldn't want to have your credit card numbers sent over the Internet in plain-text, because someone monitoring the Internet might see your credit card information whiz by. Rather, you'd want to send your credit card information as an encrypted message. When this encrypted message was received by the Web server, it could be decrypted, resulting in the actual credit card numbers.

One-way encryption, on the other hand, only allows for a plain-text input to be encrypted. That is, there is no way to decrypt the data. At first it may seem that such an encryption scheme is not needed - after all, why would you only want to be able to encrypt data and not decrypt it? A practical example of this is storing encrypted passwords on a database server, which is what this article is all about! That is, when a user creates a new account, he or she will supply their password. Rather than storing this password to the database as plain text, this password can be encrypted using a one-way encrypting algorithm and its encrypted form can be saved to the database. That way, if someone gains access to the database they will not see any of the passwords in plain-text.

MD5 encryption is an example of a one-way encryption algorithm; specifically, MD5 encryption maps a plain-text string of an arbitrary length to a small encrypted string of a fixed length. Two important properties of the MD5 algorithm are that given an encrypted output it is impossible to revert back to the initial, plain-text input, and that any given input always maps to the same encrypted value. The former property means that even if a hacker sees the encrypted output of the MD5 algorithm, they can't "unwind it" and get back at the plain-text input; the latter property means that if you wish to encrypt a particular plain-text input that it will always result in the same encrypted output.

The MD5CyptoServiceProvider class in the System.Security.Cryptography namespace of the .NET Framework provides a class for performing one-way, MD5 encryption. It is this class that we'll use to provide encrypted passwords in our database. Before we examine how to implement encrypted passwords, let's take a minute to investigate the functionality of the MD5CyptoServiceProvider class. The main method of this class is the ComputeHash method, which takes as input an array of bytes (the plain-text string to encrypt) and returns an array of bytes, which is the encrypted value. Commonly we'll want to encrypt a string, meaning that we must convert our string to an array of bytes in order to use the ComputeHash method. This conversion can be accomplished by using the UTF8Encoding encoding class, as shown in the following example:

'The string we wish to encrypt
Dim strPlainText as String = "Encrypt me!"

'The array of bytes that will contain the encrypted value of strPlainText
Dim hashedDataBytes as Byte()

'The encoder class used to convert strPlainText to an array of bytes
Dim encoder as New UTF8Encoding()

'Create an instance of the MD5CryptoServiceProvider class
Dim md5Hasher as New MD5CryptoServiceProvider()

'Call ComputeHash, passing in the plain-text string as an array of bytes
'The return value is the encrypted value, as an array of bytes
hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText))
[View a Live Demo!]

Keep in mind that the ComputeHash method deals with arrays of bytes, not strings. Hence, to encrypt a plain-text string you must convert it to an array of bytes. This is accomplished by using the UTF8Encoding encoding class's GetBytes method (see the last line of the above code example). The return result of the ComputeHash method is the encrypted data as an array of bytes. (For all practical purposes, the encrypted array has exactly 16 elements.)

Now that we've discussed the motivation behind using encrypted passwords and looked at the MD5 encryption algorithm, let's turn our attention to actually implementing encrypted passwords using MD5. We'll examine this, and more




Extensible Markup Language

The Extensible Markup Language (XML) is a general-purpose markup language.[1] It is classified as an extensible language because it allows its users to define their own elements. Its primary purpose is to facilitate the sharing of structured data across different information systems, particularly via the Internet.[2] It is used both to encode documents and serialize data. In the latter context, it is comparable with other text-based serialization languages such as JSON and YAML.[3]

It started as a simplified subset of the Standard Generalized Markup Language (SGML), and is designed to be relatively human-legible. By adding semantic constraints, application languages can be implemented in XML. These include XHTML,[4] RSS, MathML, GraphML, Scalable Vector Graphics, MusicXML, and thousands of others. Moreover, XML is sometimes used as the specification language for such application languages.

XML is recommended by the World Wide Web Consortium. It is a fee-free open standard. The W3C recommendation specifies both the lexical grammar, and the requirements for parsing.

Well-formed and valid XML documents

There are two levels of correctness of an XML document:

  • Well-formed. A well-formed document conforms to all of XML's syntax rules. For example, if a start-tag appears without a corresponding end-tag, it is not well-formed. A document that is not well-formed is not considered to be XML; a conforming parser is not allowed to process it.
  • Valid. A valid document additionally conforms to some semantic rules. These rules are either user-defined, or included as an XML schema or DTD. For example, if a document contains an undefined element, then it is not valid; a validating parser is not allowed to process it.

Well-formed documents: XML syntax

As long as only well-formedness is required, XML is a generic framework for storing any amount of text or any data whose structure can be represented as a tree. The only indispensable syntactical requirement is that the document has exactly one root element (alternatively called the document element). This means that the text must be enclosed between a root start-tag and a corresponding end-tag. The following is a "well-formed" XML document:

<book>This is a book.... </book>

The root element can be preceded by an optional XML declaration. This element states what version of XML is in use (normally 1.0); it may also contain information about character encoding and external dependencies.

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

The specification requires that processors of XML support the pan-Unicode character encodings UTF-8 and UTF-16 (UTF-32 is not mandatory). The use of more limited encodings, such as those based on ISO/IEC 8859, is acknowledged and is widely used and supported.

Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.

XML comments start with <!-- and end with -->. Two dashes (--) may not appear anywhere in the text of the comment.

<!-- This is a comment. -->

In any meaningful application, additional markup is used to structure the contents of the XML document. The text enclosed by the root tags may contain an arbitrary number of XML elements. The basic syntax for one element is:

<name attribute="value">content</name>

The two instances of »name« are referred to as the start-tag and end-tag, respectively. Here, »content« is some text which may again contain XML elements. So, a generic XML document contains a tree-based data structure. Here is an example of a structured XML document:

<recipe name="bread" prep_time="5 mins" cook_time="3 hours">
   <title>Basic bread</title>
   <ingredient amount="3" unit="cups">Flour</ingredient>
   <ingredient amount="0.25" unit="ounce">Yeast</ingredient>
   <ingredient amount="1.5" unit="cups" state="warm">Water</ingredient>
   <ingredient amount="1" unit="teaspoon">Salt</ingredient>
     <step>Mix all ingredients together.</step>
     <step>Knead thoroughly.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Knead again.</step>
     <step>Place in a bread baking tin.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Bake in the oven at 350°F for 30 minutes.</step>

Attribute values must always be quoted, using single or double quotes; and each attribute name should appear only once in any element. XML requires that elements be properly nested — elements may never overlap. For example, the code below is not well-formed XML, because the em and strong elements overlap:

<p>Normal <em>emphasized <strong>strong emphasized</em> strong</strong></p>
<!-- Correct: Well-formed XML. -->
<p>Normal <em>emphasized <strong>strong emphasized</strong></em> <strong>strong</strong></p>
<p>Alternatively <em>emphasized</em> <strong><em>strong emphasized</em> strong</strong></p>

XML provides special syntax for representing an element with empty content. Instead of writing a start-tag followed immediately by an end-tag, a document may contain an empty-element tag. An empty-element tag resembles a start-tag but contains a slash just before the closing angle bracket. The following three examples are equivalent in XML:

<foo />

An empty-element may contain attributes:

<info author="John" genre="science-fiction" date="2009-Jan-01" />

Entity references

An entity in XML is a named body of data, usually text. Entities are often used to represent single characters that cannot easily be entered on the keyboard; they are also used to represent pieces of standard ("boilerplate") text that occur in many documents, especially if there is a need to allow such text to be changed in one place only.

Special characters can be represented either using entity references, or by means of numeric character references. An example of a numeric character reference is "", which refers to the Euro symbol by means of its Unicode codepoint in hexadecimal.

An entity reference is a placeholder that represents that entity. It consists of the entity's name preceded by an ampersand ("&") and followed by a semicolon (";"). XML has five predeclared entities:






less than



greater than






quotation mark

Here is an example using a predeclared XML entity to represent the ampersand in the name "AT&T":


Additional entities (beyond the predefined ones) can be declared in the document's Document Type Definition (DTD). A basic example of doing so in a minimal internal DTD follows. Declared entities can describe single characters or pieces of text, and can reference each other.

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

<!DOCTYPE example [

<!ENTITY copy "©">

<!ENTITY copyright-notice "Copyright © 2006, XYZ Enterprises">





When viewed in a suitable browser, the XML document above appears as:

<example> Copyright © 2006, XYZ Enterprises </example>

Numeric character references

Numeric character references look like entity references, but instead of a name, they contain the "#" character followed by a number. The number (in decimal or "x"-prefixed hexadecimal) represents a Unicode code point. Unlike entity references, they are neither predeclared nor do they need to be declared in the document's DTD. They have typically been used to represent characters that are not easily encodable, such as an Arabic character in a document produced on a European computer. The ampersand in the "AT&T" example could also be escaped like this (decimal 38 and hexadecimal 26 both represent the Unicode code point for the "&" character):



Similarly, in the previous example, notice that “&#xA9” is used to generate the “©” symbol.

See also numeric character references.

Well-formed documents

A well-formed document must conform to the following rules, among others:

  • Non-empty elements are delimited by both a start-tag and an end-tag.
  • Empty elements may be marked with an empty-element (self-closing) tag, such as <IAmEmpty />. This is equal to <IAmEmpty></IAmEmpty>.
  • All attribute values are quoted with either single (') or double (") quotes. Single quotes close a single quote and double quotes close a double quote.
  • Tags may be nested but must not overlap. Each non-root element must be completely contained in another element.
  • The document complies with its declared character encoding. The encoding may be declared or implied externally, such as in "Content-Type" headers when a document is transported via HTTP, or internally, using explicit markup at the very beginning of the document. When no such declaration exists, a Unicode encoding is assumed, as defined by a Unicode Byte Order Mark before the document's first character. If the mark does not exist, UTF-8 encoding is assumed.

Element names are case-sensitive. For example, the following is a well-formed matching pair:

<Step> ... </Step>

whereas this is not

<Step> ... </step>

The careful choice of names for XML elements will convey the meaning of the data in the markup. This increases human readability while retaining the rigor needed for software parsing.

Choosing meaningful names implies the semantics of elements and attributes to a human reader without reference to external documentation. However, this can lead to verbosity, which complicates authoring and increases file size.

Automatic verification

It is relatively simple to verify that a document is well-formed or validated XML, because the rules of well-formedness and validation of XML are designed for portability of tools. The idea is that any tool designed to work with XML files will be able to work with XML files written in any XML language (or XML application). One example of using an independent tool follows:

  • load it into an XML-capable browser, such as Firefox or Internet Explorer
  • use a tool like xmlwf (usually bundled with expat)
  • parse the document, for instance in Ruby:

irb> require "rexml/document"

irb> include REXML

irb> doc ="test.xml")).root

Valid documents: XML semantics

By leaving the names, allowable hierarchy, and meanings of the elements and attributes open and definable by a customizable schema or DTD, XML provides a syntactic foundation for the creation of purpose specific, XML-based markup languages. The general syntax of such languages is rigid — documents must adhere to the general rules of XML, ensuring that all XML-aware software can at least read and understand the relative arrangement of information within them. The schema merely supplements the syntax rules with a set of constraints. Schemas typically restrict element and attribute names and their allowable containment hierarchies, such as only allowing an element named 'birthday' to contain 1 element named 'month' and 1 element named 'day', each of which has to contain only character data. The constraints in a schema may also include data type assignments that affect how information is processed; for example, the 'month' element's character data may be defined as being a month according to a particular schema language's conventions, perhaps meaning that it must not only be formatted a certain way, but also must not be processed as if it were some other type of data.

An XML document that complies with a particular schema/DTD, in addition to being well-formed, is said to be valid.

An XML schema is a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic constraints imposed by XML itself. A number of standard and proprietary XML schema languages have emerged for the purpose of formally expressing such schemas, and some of these languages are XML-based, themselves.

Before the advent of generalised data description languages such as SGML and XML, software designers had to define special file formats or small languages to share data between programs. This required writing detailed specifications and special-purpose parsers and writers.

XML's regular structure and strict parsing rules allow software designers to leave parsing to standard tools, and since XML provides a general, data model-oriented framework for the development of application-specific languages, software designers need only concentrate on the development of rules for their data, at relatively high levels of abstraction.

Well-tested tools exist to validate an XML document "against" a schema: the tool automatically verifies whether the document conforms to constraints expressed in the schema. Some of these validation tools are included in XML parsers, and some are packaged separately.

Other usages of schemas exist: XML editors, for instance, can use schemas to support the editing process (by suggesting valid elements and attributes names, etc).


Main article: Document Type Definition

The oldest schema format for XML is the Document Type Definition (DTD), inherited from SGML. While DTD support is ubiquitous due to its inclusion in the XML 1.0 standard, it is seen as limited for the following reasons:

  • It has no support for newer features of XML, most importantly namespaces.
  • It lacks expressiveness. Certain formal aspects of an XML document cannot be captured in a DTD.
  • It uses a custom non-XML syntax, inherited from SGML, to describe the schema.

DTD is still used in many applications because it is considered the easiest to read and write.

XML Schema

Main article: XML Schema (W3C)

A newer XML schema language, described by the W3C as the successor of DTDs, is XML Schema, or more informally referred to by the initialism for XML Schema instances, XSD (XML Schema Definition). XSDs are far more powerful than DTDs in describing XML languages. They use a rich datatyping system, allow for more detailed constraints on an XML document's logical structure, and must be processed in a more robust validation framework. XSDs also use an XML-based format which makes it possible to use ordinary XML tools to help process them, although XSD implementations require much more than just the ability to read XML.

Criticisms of XSD include the following:

  • The specification is very large, which makes it difficult to understand and implement.
  • The XML-based syntax leads to verbosity in schema description, which makes XSDs harder to read and write.
  • Schema validation can be an expensive addition to XML parsing, especially for high volume systems.
  • The modeling capabilities are very limited, with no ability to allow attributes to influence content models.
  • The type derivation model is very limited, in particular that derivation by extension is rarely useful.
  • Database-related data transfer has been supported with arcane ideas such as nillability but the requirements of industrial publishing are under-supported.
  • The key/keyref/uniqueness mechanisms are not type aware
  • The PSVI concept (Post Schema Validation Infoset) does not have a standard XML representation or Application Programming Interface, thus it works against vendor independence unless revalidation is performed.


Main article: RELAX NG

Another popular schema language for XML is RELAX NG. Initially specified by OASIS, RELAX NG is now also an ISO international standard (as part of DSDL). It has two formats: an XML based syntax and a non-XML compact syntax. The compact syntax aims to increase readability and writability but, since there is a well-defined way to translate the compact syntax to the XML syntax and back again by means of James Clark's Trang conversion tool, the advantage of using standard XML tools is not lost. RELAX NG has a simpler definition and validation framework than XML Schema, making it easier to use and implement. It also has the ability to use datatype framework plug-ins; a RELAX NG schema author, for example, can require values in an XML document to conform to definitions in XML Schema Datatypes.

ISO DSDL and Other Schema Languages

The ISO DSDL (Document Schema Description Languages) standard brings together a comprehensive set of small schema languages, each targeted at specific problems. DSDL includes RELAX NG full and compact syntax, Schematron assertion language, and languages for defining datatypes, character repertoire constraints, renaming and entity expansion, and namespace-based routing of document fragments to different validators. DSDL schema languages do not have the vendor support of XML Schemas yet, and are to some extent a grassroots reaction of industrial publishers to the lack of utility of XML Schemas for publishing.

Some schema languages not only describe the structure of a particular XML format but also offer limited facilities to influence processing of individual XML files that conform to this format. DTDs and XSDs both have this ability; they can for instance provide attribute defaults. RELAX NG and Schematron intentionally do not provide these; for example the infoset augmentation facility.

International use

XML supports the direct use of almost any Unicode character (other than the ones that have special symbolic meaning in XML, itself, such as the open corner bracket, "<") in element names, attributes, comments, character data, and processing instructions. Therefore, the following is a well-formed XML document, even though it includes both Chinese and Cyrillic characters:

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


Displaying XML on the web

XML documents do not carry information about how to display the data. Without using CSS or XSL, a generic XML document is rendered as raw XML text by most web browsers. Some display it with 'handles' (e.g. + and - signs in the margin) that allow parts of the structure to be expanded or collapsed with mouse-clicks.

In order to style the rendering in a browser with CSS, the XML document must include a reference to the stylesheet:

<?xml-stylesheet type="text/css" href="myStyleSheet.css"?>

Note that this is different from specifying such a stylesheet in HTML, which uses the <link> element.

Extensible Stylesheet Language (XSL) can be used to alter the format of XML data, either into HTML or other formats that are suitable for a browser to display.

To specify client-side XSL Transformation (XSLT), the following processing instruction is required in the XML:

<?xml-stylesheet type="text/xsl" href="myTransform.xslt"?>

Client-side XSLT is supported by many web browsers, but not Opera before version 9.0. Alternatively, one may use XSL to convert XML into a displayable format on the server rather than being dependent on the end-user's browser capabilities. The end-user is not aware of what has gone on 'behind the scenes'; all they see is well-formatted, displayable data.

See the XSLT article for an example of server-side XSLT in action.

XML extensions

  • XPath makes it possible to refer to individual parts of an XML document. This provides random access to XML data for other technologies, including XSLT, XSL-FO, XQuery etc. XPath expressions can refer to all or part of the text, data and values in XML elements, attributes, processing instructions, comments etc. They can also access the names of elements and attributes. XPaths can be used in both valid and well-formed XML, with and without defined namespaces.
  • XInclude defines the ability for XML files to include all or part of an external file. When processing is complete, the final XML infoset has no XInclude elements, but instead has copied the documents or parts thereof into the final infoset. It uses XPath to refer to a portion of the document for partial inclusions.
  • XQuery is to XML what SQL and PL/SQL are to relational databases: ways to access, manipulate and return XML.
  • XML Namespaces enable the same document to contain XML elements and attributes taken from different vocabularies, without any naming collisions occurring.
  • XML Signature defines the syntax and processing rules for creating digital signatures on XML content.
  • XML Encryption defines the syntax and processing rules for encrypting XML content.
  • XPointer is a system for addressing components of XML-based internet media.

XML files may be served with a variety of Media types. RFC 3023 defines the types "application/xml" and "text/xml", which say only that the data is in XML, and nothing about its semantics. The use of "text/xml" has been criticized as a potential source of encoding problems but is now in the process of being deprecated.[5] RFC 3023 also recommends that XML-based languages be given media types beginning in "application/" and ending in "+xml"; for example "application/atom+xml" for Atom. This page discusses further XML and MIME.

Processing XML files

Three traditional techniques for processing XML files are:

  • Using a programming language and the SAX API.
  • Using a programming language and the DOM API.
  • Using a transformation engine and a filter

More recent and emerging techniques for processing XML files are:

  • Push Parsing
  • Data binding

Simple API for XML (SAX)

SAX is a lexical, event-driven interface in which a document is read serially and its contents are reported as "callbacks" to various methods on a handler object of the user's design. SAX is fast and efficient to implement, but difficult to use for extracting information at random from the XML, since it tends to burden the application author with keeping track of what part of the document is being processed. It is better suited to situations in which certain types of information are always handled the same way, no matter where they occur in the document.


DOM is an interface-oriented Application Programming Interface that allows for navigation of the entire document as if it were a tree of "Node" objects representing the document's contents. A DOM document can be created by a parser, or can be generated manually by users (with limitations). Data types in DOM Nodes are abstract; implementations provide their own programming language-specific bindings. DOM implementations tend to be memory intensive, as they generally require the entire document to be loaded into memory and constructed as a tree of objects before access is allowed. DOM is supported in Java by several packages that usually come with the standard libraries. As the DOM specification is regulated by the World Wide Web Consortium, the main interfaces (Node, Document, etc.) are in the package org.w3c.dom.*, as well as some of the events and interfaces for other capabilities like serialization (output). The package* provides the serialization (output capacities) by impementing the appropriate interfaces, while the javax.xml.parsers.* package parses data to create DOM XML documents for manipulation. [2]

Transformation engines and filters

A filter in the Extensible Stylesheet Language (XSL) family can transform an XML file for displaying or printing.

  • XSL-FO is a declarative, XML-based page layout language. An XSL-FO processor can be used to convert an XSL-FO document into another non-XML format, such as PDF.
  • XSLT is a declarative, XML-based document transformation language. An XSLT processor can use an XSLT stylesheet as a guide for the conversion of the data tree represented by one XML document into another tree that can then be serialized as XML, HTML, plain text, or any other format supported by the processor.
  • XQuery is a W3C language for querying, constructing and transforming XML data.
  • XPath is a DOM-like node tree data model and path expression language for selecting data within XML documents. XSL-FO, XSLT and XQuery all make use of XPath. XPath also includes a useful function library.

Pull Parsing

Pull parsing [6] treats the document as a series of items which are read in sequence using the Iterator design pattern. This allows for writing of recursive-descent parsers in which the structure of the code performing the parsing mirrors the structure of the XML being parsed, and intermediate parsed results can be used and accessed as local variables within the methods performing the parsing, or passed down (as method parameters) into lower-level methods, or returned (as method return values) to higher-level methods. Examples of pull parsers include StAX in the Java programming language, SimpleXML in PHP and System.Xml.XmlReader in .NET.

A pull parser creates an iterator that sequentially visits the various elements, attributes, and data in an XML document. Code which uses this 'iterator' can test the current item (to tell, for example, whether it is a start or end element, or text), and inspect its attributes (local name, namespace, values of XML attributes, value of text, etc.), and can also move the iterator to the 'next' item. The code can thus extract information from the document as it traverses it. The recursive-descent approach tends to lend itself to keeping data as typed local variables in the code doing the parsing, while SAX, for instance, typically requires a parser to manually maintain intermediate data within a stack of elements which are parent elements of the element being parsed. Pull-parsing code can be more straightforward to understand and maintain than SAX parsing code.

Data binding

Another form of XML Processing API is data binding, where XML data is made available as a custom, strongly typed programming language data structure, in contrast to the interface-oriented DOM. Example data binding systems include the Java Architecture for XML Binding (JAXB)[7].

Non-extractive XML Processing API

Non-extractive XML Processing API is a new and emerging category of parsers that aim to overcome the fundamental limitations of DOM and SAX. The most representative is VTD-XML, which abolishes the object-oriented modeling of XML hierarchy and instead uses 64-bit Virtual Token Descriptors (encoding offsets, lengths, depths, and types) of XML tokens. VTD-XML's approach enables a number of interesting features/enhancements, such as high performance, low memory usage [8], ASIC implementation [9], incremental update [10], and native XML indexing [11] [12].

[edit] Specific XML applications and editors

The native file format of, AbiWord, and Apple's iWork applications is XML. Some parts of Microsoft Office 2007 are also able to edit XML files with a user-supplied schema (but not a DTD), and Microsoft has released a file format compatibility kit for Office 2003 that allows previous versions of Office to save in the new XML based format. There are dozens of other XML editors available.


The versatility of SGML for dynamic information display was understood by early digital media publishers in the late 1980s prior to the rise of the Internet.[13][14] By the mid-1990s some practitioners of SGML had gained experience with the then-new World Wide Web, and believed that SGML offered solutions to some of the problems the Web was likely to face as it grew. Dan Connolly added SGML to the list of W3C's activities when he joined the staff in 1995; work began in mid-1996 when Jon Bosak developed a charter and recruited collaborators. Bosak was well connected in the small community of people who had experience both in SGML and the Web. He received support in his efforts from Microsoft.

XML was compiled by a working group of eleven members,[15] supported by an (approximately) 150-member Interest Group. Technical debate took place on the Interest Group mailing list and issues were resolved by consensus or, when that failed, majority vote of the Working Group. A record of design decisions and their rationales was compiled by Michael Sperberg-McQueen on December 4th 1997.[16] James Clark served as Technical Lead of the Working Group, notably contributing the empty-element "<empty/>" syntax and the name "XML". Other names that had been put forward for consideration included "MAGMA" (Minimal Architecture for Generalized Markup Applications), "SLIM" (Structured Language for Internet Markup) and "MGML" (Minimal Generalized Markup Language). The co-editors of the specification were originally Tim Bray and Michael Sperberg-McQueen. Halfway through the project Bray accepted a consulting engagement with Netscape, provoking vociferous protests from Microsoft. Bray was temporarily asked to resign the editorship. This led to intense dispute in the Working Group, eventually solved by the appointment of Microsoft's Jean Paoli as a third co-editor.

The XML Working Group never met face-to-face; the design was accomplished using a combination of email and weekly teleconferences. The major design decisions were reached in twenty weeks of intense work between July and November of 1996, when the first Working Draft of an XML specification was published.[17] Further design work continued through 1997, and XML 1.0 became a W3C Recommendation on February 10, 1998.

XML 1.0 achieved the Working Group's goals of Internet usability, general-purpose usability, SGML compatibility, facilitation of easy development of processing software, minimization of optional features, legibility, formality, conciseness, and ease of authoring. Like its antecedent SGML, XML allows for some redundant syntactic constructs and includes repetition of element identifiers. In these respects, terseness was not considered essential in its structure.


XML is a profile of an ISO standard SGML, and most of XML comes from SGML unchanged. From SGML comes the separation of logical and physical structures (elements and entities), the availability of grammar-based validation (DTDs), the separation of data and metadata (elements and attributes), mixed content, the separation of processing from representation (processing instructions), and the default angle-bracket syntax. Removed were the SGML Declaration (XML has a fixed delimiter set and adopts Unicode as the document character set).

Other sources of technology for XML were the Text Encoding Initiative (TEI), which defined a profile of SGML for use as a 'transfer syntax'; HTML, in which elements were synchronous with their resource, the separation of document character set from resource encoding, the xml:lang attribute, and the HTTP notion that metadata accompanied the resource rather than being needed at the declaration of a link; and the Extended Reference Concrete Syntax (ERCS), from which XML 1.0's naming rules were taken, and which had introduced hexadecimal numeric character references and the concept of references to make available all Unicode characters.

Ideas that developed during discussion which were novel in XML, were the algorithm for encoding detection and the encoding header, the processing instruction target, the xml:space attribute, and the new close delimiter for empty-element tags.


There are two current versions of XML. The first, XML 1.0, was initially defined in 1998. It has undergone minor revisions since then, without being given a new version number, and is currently in its fourth edition, as published on August 16, 2006. It is widely implemented and still recommended for general use. The second, XML 1.1, was initially published on February 4, 2004, the same day as XML 1.0 Third Edition, and is currently in its second edition, as published on August 16, 2006. It contains features — some contentious — that are intended to make XML easier to use in certain cases[18] - mainly enabling the use of line-ending characters used on EBCDIC platforms, and the use of scripts and characters absent from Unicode 2.0. XML 1.1 is not very widely implemented and is recommended for use only by those who need its unique features. [19]

XML 1.0 and XML 1.1 differ in the requirements of characters used for element and attribute names: XML 1.0 only allows characters which are defined in Unicode 2.0, which includes most world scripts, but excludes those which were added in later Unicode versions. Among the excluded scripts are Mongolian, Cambodian, Amharic, Burmese, and others.

Almost any Unicode character can be used in the character data and attribute values of an XML 1.1 document, even if the character is not defined, aside from having a code point, in the current version of Unicode. The approach in XML 1.1 is that only certain characters are forbidden, and everything else is allowed, whereas in XML 1.0, only certain characters are explicitly allowed, thus XML 1.0 cannot accommodate the addition of characters in future versions of Unicode.

In character data and attribute values, XML 1.1 allows the use of more control characters than XML 1.0, but, for "robustness", most of the control characters introduced in XML 1.1 must be expressed as numeric character references. Among the supported control characters in XML 1.1 are two line break codes that must be treated as whitespace. Whitespace characters are the only control codes that can be written directly.

There are also discussions on an XML 2.0, although it remains to be seen[vague] if such will ever come about. XML-SW (SW for skunk works), written by one of the original developers of XML, contains some proposals for what an XML 2.0 might look like: elimination of DTDs from syntax, integration of namespaces, XML Base and XML Information Set (infoset) into the base standard.

The World Wide Web Consortium also has an XML Binary Characterization Working Group doing preliminary research into use cases and properties for a binary encoding of the XML infoset. The working group is not chartered to produce any official standards. Since XML is by definition text-based, ITU-T and ISO are using the name Fast Infoset[3] for their own binary infoset to avoid confusion (see ITU-T Rec. X.891 | ISO/IEC 24824-1).

Patent claims

In October 2005 the small company Scientigo publicly asserted that two of its patents, U.S. Patent 5,842,213 and U.S. Patent 6,393,426 , apply to the use of XML. The patents cover the "modeling, storage and transfer [of data] in a particular non-hierarchical, non-integrated neutral form", according to their applications, which were filed in 1997 and 1999. Scientigo CEO Doyal Bryant expressed a desire to "monetize" the patents but stated that the company was "not interested in having us against the world." He said that Scientigo was discussing the patents with several large corporations.[20]

XML users and independent experts responded to Scientigo's claims with widespread skepticism and criticism. Some derided the company as a patent troll. Tim Bray described any claims that the patents covered XML as "ridiculous on the face of it".[21]

Because there exists a large amount of prior art relating to XML, including SGML, some legal experts believed it would be difficult for Scientigo to enforce its patents through litigation.[citation needed]

Critique of XML

Commentators have offered various critiques of XML, suggesting circumstances where XML provides both advantages and potential disadvantages.[22]

XML is really just data dressed up as a hooker.

Dave Thomas[23]

Advantages of XML

  • It is text-based.
  • It supports Unicode, allowing almost any information in any written human language to be communicated.
  • It can represent common computer science data structures: records, lists and trees.
  • Its self-documenting format describes structure and field names as well as specific values.
  • The strict syntax and parsing requirements make the necessary parsing algorithms extremely simple, efficient, and consistent.
  • XML is heavily used as a format for document storage and processing, both online and offline.
  • It is based on international standards.
  • It can be updated incrementally.
  • It allows validation using schema languages such as XSD and Schematron, which makes effective unit-testing, firewalls, acceptance testing, contractual specification and software construction easier.
  • The hierarchical structure is suitable for most (but not all) types of documents.
  • It manifests as plain text files, which are less restrictive than other proprietary document formats.
  • It is platform-independent, thus relatively immune to changes in technology.
  • Forward and backward compatibility are relatively easy to maintain despite changes in DTD or Schema.
  • Its predecessor, SGML, has been in use since 1986, so there is extensive experience and software available.
  • An element fragment of a well-formed XML document is also a well-formed XML document.

Disadvantages of XML

  • XML syntax is redundant or large relative to binary representations of similar data.[24]
  • The redundancy may affect application efficiency through higher storage, transmission and processing costs.[25][26]
  • XML syntax is verbose, especially for human readers, relative to other alternative 'text-based' data transmission formats.[27][28]
  • The hierarchical model for representation is limited in comparison to an object oriented graph.[29][30]
  • Expressing overlapping (non-hierarchical) node relationships requires extra effort.[31]
  • XML namespaces are problematic to use and namespace support can be difficult to correctly implement in an XML parser.[32]
  • XML is commonly depicted as "self-documenting" but this depiction ignores critical ambiguities.[33][34]
  • The distinction between content and attributes in XML seems unnatural to some and makes designing XML data structures harder.[35]
  • Linking between XML documents requires the use of XLink, which is complex compared to hyperlinks[36]
  • It's hard to find an XML parser that is complete, correct, and efficient.[37]