Share your knowledge and create a knowledgebase.
When working with XML-based applications, developers often find themselves facing the requirement to generate XML-encoded data structures on the fly. Examples of this include an XML order template based on user input in a Web form, or an XML representation of a server request or client response based on run-time parameters.
Although this task might seem intimidating, it’s actually quite simple when one takes into account PHP’s sophisticated DOM API for dynamic node construction and manipulation. Over the course of this article, I’ll be introducing you to the main functions in this API, showing you how to programmatically generate a complete well-formed XML document from scratch and save it to disk.
Note: This article assumes a working Apache/PHP5 installation with the DOM functions enabled, and a working knowledge of basic XML constructs such as elements, attributes and CDATA blocks. You can obtain an introduction to these topics from the introductory material at Melonfire (http://melonfire.com/community/columns/trog/article.php?id=78 and http://melonfire.com/community/columns/trog/article.php?id=79)
Creating the Doctype declaration
Let’s start right at the top, with the XML declaration. In PHP, this is fairly simple; it only requires you to instantiate an object of the DOMDocument class and supply it with a version number. To see it in action type out the example script in Listing A.
Listing A
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // save and display tree echo $dom->saveXML(); ?>
Notice the saveXML() method of the DOMDocument object — I’ll come back to this later, but for the moment simply realise that this is the method used to output a current snapshot of the XML tree, either to a file or to the browser. In this case, I’ve sent the output directly to the browser as ASCII text for readability purposes; in real-world applications, you would probably send this with a Content-Type: text/xml header.
When you view the output in your browser, you should see something like this:
<?xml version="1.0"?>Adding elements and text nodes
Now that’s all very pretty and fine, but the real power of XML comes from its elements and the content they enclose. Fortunately, once you’ve got the basic DOMDocument initialised, this becomes extremely simple. There are two steps to the process:
1. For each element or text node you wish to add, call the DOMDocument object’s createElement() or createTextNode() method with the element name or text content. This will result in the creation of a new object corresponding to the element or text node.
2. Append the element or text node to a parent node in the XML tree by calling that node’s appendChild() method and passing it the object produced in the previous step.
An example will make this clearer. Consider the script in Listing B.
Listing B
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // save and display tree echo $dom->saveXML(); ?>
Here, I’ve first created a root element named
<?xml version="1.0"?> <toppings> <item>pepperoni</item> </toppings>
If you’d like to add another topping, simply create another
Listing C
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create another text node $text = $dom->createTextNode("tomato"); $item->appendChild($text); // save and display tree echo $dom->saveXML(); ?>
And here’s the revised output:
<?xml version="1.0"?> <toppings> <item>pepperoni</item> <item>tomato</item> </toppings>
Adding attributes
You can also add qualifying information to your elements, through the thoughtful use of attributes. With the PHP DOM API, attributes are added in a two-step process: first create an attribute node holding the name of the attribute with the DOMDocument object’s createAttribute() method, and then append a text node to it holding the attribute value. Listing D is an example.
Listing D
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // save and display tree echo $dom->saveXML(); ?>
And here’s what the output will look like:
<?xml version="1.0"?> <toppings> <item price="4">pepperoni</item> </toppings>
Adding CDATA blocks and processing instructions
While not used quite as often, CDATA blocks and processing instructions (PI) are also well-supported by the PHP API, through the DOMDocument object’s createCDATASection() and createProcessingInstruction() methods. Listing E shows you an example.
Listing E
<?php // create doctype $dom = new DOMDocument("1.0"); // display document in browser as plain text // for readability purposes header("Content-Type: text/plain"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // create CDATA section $cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n"); $root->appendChild($cdata); // create PI $pi = $dom->createProcessingInstruction("pizza", "bake()"); $root->appendChild($pi); // save and display tree echo $dom->saveXML(); ?>
And here’s the output:
<?xml version="1.0"?> <toppings> <item price="4">pepperoni</item> <![CDATA[ Customer requests that pizza be sliced into 16 square pieces ]]> <?pizza bake()?> </toppings>
Saving the results
Once you’ve got the tree the way you want it, you can either save it to a file or store it in a PHP variable. The former function is performed by calling the save() method with a file name, while the latter is performed by calling the saveXML() method and assigning the result to a string. Here’s an example (Listing F).
Listing F
<?php // create doctype $dom = new DOMDocument("1.0"); // create root element $root = $dom->createElement("toppings"); $dom->appendChild($root); $dom->formatOutput=true; // create child element $item = $dom->createElement("item"); $root->appendChild($item); // create text node $text = $dom->createTextNode("pepperoni"); $item->appendChild($text); // create attribute node $price = $dom->createAttribute("price"); $item->appendChild($price); // create attribute value node $priceValue = $dom->createTextNode("4"); $price->appendChild($priceValue); // create CDATA section $cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n"); $root->appendChild($cdata); // create PI $pi = $dom->createProcessingInstruction("pizza", "bake()"); $root->appendChild($pi); // save tree to file $dom->save("order.xml"); // save tree to string $order = $dom->save("order.xml"); ?>
And that’s about it. Hopefully you found this article interesting, and will be able to use these techniques in your daily work with XML. Happy coding!
XPath is a language that allows you to address parts of an XML document, making XSLT transformations practically necessary. It also makes it an invaluable tool for managing XML data in applications such as Web applications.
Microsoft provides XPath functionality through the selectSingleNode() and selectNodes() methods on DOM nodes and documents. However, PHP uses functions that provide XPath functionality through contexts. In the following example, I’ll show sample XML data and PHP code to grab different parts of the XML document. I’ll also explain how the PHP code works.
In the example code, I use the following XML data to provide the functionality. (Note: This code was developed and run successfully using PHP 4.3.4, Windows XP, and IIS 5.1.)
<?xml version="1.0"?> <x:root xmlns:x="http://www.someplace.com"> <x:row> <x:dog color="yellow">Marmaduke</x:dog> <x:cat>Garfield</x:cat> </x:row> <x:row> <x:dog color="white">Snoopy</x:dog> <x:cat>Heathcliff</x:cat> </x:row> <x:row> <x:dog color="gray">Spike</x:dog> <x:cat>Sylvester</x:cat> </x:row> </x:root>
This XML data contains a few elements and some attributes including a namespace declaration — some basic XML. This results in varied queries for me to test.
<?php $sxml = '<?xml version="1.0"?> <x:root xmlns:x="http://www.someplace.com"> <x:row> <x:dog color="yellow">Marmaduke</x:dog> <x:cat>Garfield</x:cat> </x:row> <x:row> <x:dog color="white">Snoopy</x:dog> <x:cat>Heathcliff</x:cat> </x:row> <x:row> <x:dog color="gray">Spike</x:dog> <x:cat>Sylvester</x:cat> </x:row> </x:root>'; $xml = domxml_open_mem($sxml); $xpc = xpath_new_context($xml); xpath_register_ns($xpc, "x", "http://www.someplace.com"); $nodes = xpath_eval($xpc, "//x:row/x:dog[@color='yellow']/text()"); foreach ($nodes->nodeset as $node) { print $node->content . "\n"; } $nodes = xpath_eval($xpc, "//x:row/x:dog"); foreach ($nodes->nodeset as $node) { print $xml->dump_node($node) . "\n"; } $nodes = xpath_eval($xpc, "//x:cat/child::text()|//x:dog[@color='white' or @color='gray']/text()"); foreach ($nodes->nodeset as $node) { print $node->content . "\n"; } $xml->free(); ?>
First, I create a local variable to hold the XML string. This information could have been passed in as part of a POST HTTP request. However, for this example, I’m going to include it in the code. The next step is to create a DOM Document by using the domxml_open_mem() function. This function creates a DOM Document object in memory from a valid XML string. It accepts one parameter: the XML string. Another way to accomplish this is to store the XML in a separate file and use the domxml_open_file() function to load the XML from a file. This function takes one parameter: the filename of the XML file.
Once I create the DOM Document object, I can create an XPath context with this object through the xpath_new_context() function, which takes one parameter: the current DOM Document object. This context is used to evaluate the XPath expression and is also used to register namespaces, if needed. Since my XML includes a namespace, I register the namespace with the xpath_register_ns() function. This makes it possible to create XPath queries using prefixes. The xpath_register_ns() function takes three parameters: the XPath context, the prefix, and the namespace, respectively.
Now I can run XPath queries. This is done with the xpath_eval() function, whose first parameter is the XPath context and second parameter is the XPath expression. The function returns an array of DOM Nodes. In my code, I step through the nodeset and produce some form of output.
In the first XPath example, I grab all the x:dog text elements under the x:row nodes, where the ‘color’ attribute equals ‘yellow’. This is where the XPath expression in PHP differs slightly from an XPath expression using MSXML. I include the ‘/text()’ part of the expression to return the text nodes only. With MSXML, you access the text node with the ‘text’ property. Using the ‘content’ property on the returned text node, I can get the content of the text node.
In the second example, I grab all the x:dog elements under the x:row nodes. However, I use the dump_node() method on the DOM Document object to print out the complete XML of the appropriate node. The dump_node() method accepts one parameter: the DOM Node of which you wish to dump the contents.
In the last example, I grab all the x:cat text nodes and all the x:dog text nodes where the ‘color’ attribute is ‘white’ or ‘gray’. Once again, I step through the nodeset and print out the content of each text node. Finally, I free up the DOM Document object.
The following example illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.
Consider the following XML’s
< ?xml version=’1.0′?>
< !DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
< !ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
<title>Title &plainEntity;</title>
<para>
<informaltable>
<tgroup cols="3">
<tbody>
<row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
<row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
</tbody>
</tgroup>
</informaltable>
</para>
&systemEntity;
<section id="about">
<title>About this Document</title>
<para>
<!– this is a comment –>
< ?php echo ‘Hi! This is PHP version ‘ . phpversion(); ?>
</para>
</section>
</chapter>
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
<element attrib="value"/>
&testEnt;
<?php echo "This is some more PHP code being executed."; ?>
</foo>
The following code shows how we can parse the above XML file using PHP
< ?php
$file = "xmltest.xml";
function trustedFile($file)
{
// only trust local files owned by ourselves
if (!eregi("^([a-z]+)://", $file)
&& fileowner($file) == getmyuid()) {
return true;
}
return false;
}
function startElement($parser, $name, $attribs)
{
echo "<<font color=\"#0000cc\">$name";
if (count($attribs)) {
foreach ($attribs as $k => $v) {
echo " <font color=\"#009900\">$k</font>=\"<font color=\"#990000\">$v</font>\"";
}
}
echo ">";
}
function endElement($parser, $name)
{
echo "</<font color=\"#0000cc\">$name</font>>";
}
function characterData($parser, $data)
{
echo "<b>$data</b>";
}
function PIHandler($parser, $target, $data)
{
switch (strtolower($target)) {
case "php":
global $parser_file;
// If the parsed document is "trusted", we say it is safe
// to execute PHP code inside it. If not, display the code
// instead.
if (trustedFile($parser_file[$parser])) {
eval($data);
} else {
printf("Untrusted PHP code: <i>%s</i>",
htmlspecialchars($data));
}
break;
}
}
function defaultHandler($parser, $data)
{
if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
printf(’<font color="#aa00aa">%s</font>’,
htmlspecialchars($data));
} else {
printf(’<font size="-1">%s</font>’,
htmlspecialchars($data));
}
}
function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
$publicId) {
if ($systemId) {
if (!list($parser, $fp) = new_xml_parser($systemId)) {
printf("Could not open entity %s at %s\n", $openEntityNames,
$systemId);
return false;
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($parser, $data, feof($fp))) {
printf("XML error: %s at line %d while parsing entity %s\n",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser), $openEntityNames);
xml_parser_free($parser);
return false;
}
}
xml_parser_free($parser);
return true;
}
return false;
}
function new_xml_parser($file)
{
global $parser_file;
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
xml_set_processing_instruction_handler($xml_parser, "PIHandler");
xml_set_default_handler($xml_parser, "defaultHandler");
xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");
if (!($fp = @fopen($file, "r"))) {
return false;
}
if (!is_array($parser_file)) {
settype($parser_file, "array");
}
$parser_file[$xml_parser] = $file;
return array($xml_parser, $fp);
}
if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
die("could not open XML input");
}
echo "<pre>";
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d\n",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
echo "</pre>";
echo "parse complete\n";
xml_parser_free($xml_parser);
?>
I hope this will help. Your comments are welcome.
By handling mime-types and using browser detection, CodeHelp has already shown how to export XML using a PHP script. PHP can also receive XML as input - using the XML parser:
if (!($fp=@fopen("./contactsbare.xml", "r")))
die ("Couldn’t open XML.");
$usercount=0;
$userdata=array();
$state=”;
if (!($xml_parser = xml_parser_create()))
die("Couldn’t create parser.");
Each XML file can have it’s own DTD or structure. The PHP file using the XML parser must be tailored to one particular structure or DTD - it will then be able to read all files that are valid under that DTD. This example will use an over-simplified contacts format for XML - you will need to adapt the details of the tags (or nodes) for your own DTD. To follow the construction of the XML parser, load the example XML file into another window using the link in the Navigation Bar. (If the file doesn’t open in a new window in your browser, right click the link and choose Open in a New Window.) Multiple contacts can be specified by repeating the CONTACT tag and the PHP file therefore needs to keep track of the number of contacts used in this example. In the above code, $usercount is set to zero ready to hold the number of contacts found. $userdata will later be filled with data for each contact and $state is used to keep track of which node the parser is dealing with for each contact.
The PHP XML parser now needs two functions to be declared, one to handle the element data and one to handle the character data within the elements. This is where you need to change the code to reflect your own XML files - change the element and attribute names. I’ll start with the Element Handler. This is in two parts, a function to detect the start of real data and a function to detect when an element comes to an end - in this case to register when more than one contact is specified. Each function is called once for each node - use a switch statement to decide what action to take depending on which node is being processed. The parser will take care of the $name and $attrib variables.
function startElementHandler ($parser,$name,$attrib){
global $usercount;
global $userdata;
global $state;
switch ($name) {
case $name=="NAME" : {
$userdata[$usercount]["first"] = $attrib["FIRST"];
$userdata[$usercount]["last"] = $attrib["LAST"];
$userdata[$usercount]["nick"] = $attrib["NICK"];
$userdata[$usercount]["title"] = $attrib["TITLE"];
break;
}
}
}
function endElementHandler ($parser,$name){
global $usercount;
global $userdata;
global $state;
$state=”;
if($name=="CONTACT") {$usercount++;}
}
The function "startElementHandler()" has been abbreviated here by removing the other case $name=="" : {} statements, the full file will be looked at later.
Next, we need the character handler:
function characterDataHandler ($parser, $data) {
global $usercount;
global $userdata;
global $state;
if (!$state) {return;}
if ($state=="COMPANY") { $userdata[$usercount]["bcompany"] = $data;}
if ($state=="GENDER") { $userdata[$usercount]["gender"] = $data;}
}
Finally, tell the parser which functions to use, read the data from the opened file and parse the contents.
xml_set_element_handler($xml_parser,"startElementHandler","endElementHandler");
xml_set_character_data_handler( $xml_parser, "characterDataHandler");
while( $data = fread($fp, 4096)){
if(!xml_parse($xml_parser, $data, feof($fp))) {
break;}}
xml_parser_free($xml_parser);
The data from the XML file is now held in $userdata and can be accessed using a standard PHP loop:
for ($i=0;$i<$usercount; $i++) {
echo "Name: ".$userdata[$i]["title"]." ".
ucfirst($userdata[$i]["first"])." ". ucfirst($userdata[$i]["last"]);
}
Extensible Markup Language (XML) is a general-purpose specification for creating custom markup languages. 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, and it is used both to encode documents and to serialize data.
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"?>
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>
<instructions>
<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>
</instructions>
</recipe>
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:
& & ampersand
< < less than
> > greater than
' ‘ apostrophe
" " quotation mark
Here is an example using a predeclared XML entity to represent the ampersand in the name "AT&T":
<company_name>AT&T</company_name>
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, hurricanesoftwares.com">
]>
<example>
©right-notice;
</example>
When viewed in a suitable browser, the XML document above appears as:
<example> Copyright © 2006, Hurricanesoftwares.com </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):
<company_name>AT&T</company_name>
<company_name>AT&T</company_name>
Well-formed documents
In XML, 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>
By carefully choosing the names of the XML elements one may 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 = Document.new(File.new("test.xml")).root
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. 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.
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:
* Pull 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
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 com.sun.org.apache.xml.internal.serialize.* provides the serialization (output capacities) by implementing the appropriate interfaces, while the javax.xml.parsers.* package parses data to create DOM XML documents for manipulation.
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).
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, ASIC implementation, incremental update, and native XML indexing .
Specific XML applications and editors
The native file format of OpenOffice.org, 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.
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 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, especially with tabular data.
* The redundancy may affect application efficiency through higher storage, transmission and processing costs.
* XML syntax is verbose, especially for human readers, relative to other alternative ‘text-based’ data transmission formats.
* The hierarchical model for representation is limited in comparison to an object oriented graph.
* Expressing overlapping (non-hierarchical) node relationships requires extra effort.
* XML namespaces are problematic to use and namespace support can be difficult to correctly implement in an XML parser.
* XML is commonly depicted as "self-documenting" but this depiction ignores critical ambiguities.
* The distinction between content and attributes in XML seems unnatural to some and makes designing XML data structures harder