Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

XML and Scripting Languages

By Parand Tony Darugar
2005-05-18


Simple substitution

A simple method for transforming the XML source into HTML is to define pieces of HTML to be substituted for each XML tag. Using the popular XML::Parser module for Perl (see Resources), based on James Clark's Expat parser, we can parse the XML document and define callback routines for performing the substitutions.

Here is a simple invocation of the XML::Parser:



use XML::Parser;

my $parser = new XML::Parser(ErrorContext => 2);
$parser->setHandlers(Start => \&start_handler,
End => \&end_handler,
Char => \&char_handler);

$parser->parsefile($file);

This parses the given file, invoking the function start_handler each time a tag is started, and end_handler each time a tag is ended. The contents of the tag are processed by the char_handler function.

Given these callback functions, we can implement our simple substitution algorithm. First, we define a few substitutions:



%startsub = (
"stock_quote" => "<hr><p>",
"symbol" => "<h2>",
"price" => "<br><b>Price:</b>"
);

%endsub = (
"stock_quote" => "",
"symbol" => "</h2>",
"price" => ""
);

And now we write the handlers to perform the substitutions:



sub start_handler
{
my $expat = shift; my $element = shift;

# element is the name of the tag
print $startsub{$element};
}

sub char_handler
{
my ($p, $data) = @_;
print $data;

}

The start_handler function simply prints the value to be substituted for the given tag. char_handler outputs the data it receives, which is the content of the tags. (The full program, with a few additions to handle attributes, is listed separately.) Running the program on our XML file, we get the following output:



<hr><p>
<h2>IBM</h2>

<br><b>Date:</b><i>12/16/1999</i>
<br><b>Time:</b><i>4:40PM</i>

<br><b>Price:</b>type=ask value=109.1875
<br><b>Price:</b>type=open value=108
<br><b>Price:</b>type=dayhigh value=109.6875
<br><b>Price:</b>type=daylow value=105.75
<br><b>Change:</b>+2.1875
<br><b>Volume:</b>7050200

The full output is available. Using this methodology, we can make simple XML to HTML transformations by defining substitutions.



Tutorial Pages:
» Converting XML to HTML
» Simple substitution
» Function-based substitution
» Tree-based processing
» Active XML documents
» Storing tag contents
» Retrieving the rules
» Acting on the rules
» Next steps
» Resources


First published by IBM DeveloperWorks


 | Bookmark
Related Tutorials:
» Starting with XML
» Performing Client-Side XSL Transformations
» Create a Google Sitemap for your Web Site
» Parsing Comma-Separated Values
» XML Security Suite: Increasing the Security of E-Business
» Servlets and XML: Made for Each Other