XML and Scripting Languages
By Parand Tony Darugar2005-05-18
Function-based substitution
Substitution-based transformations are easy to implement and understand, but don't give us the ability to implement logic. We may want to take different actions based on the contents or attributes of a tag, or connect to a database to compare the contents of the tag with the stored value. We need more than simple, one-to-one substitutions; we need the ability to perform functions for each tag.
XML::Parser provides a method for invoking functions for each tag in the XML document. For each tag, the parsing module calls a function with the tag's name. Thus we can define a set of functions that perform the transformations, connect to databases, and implement our business logic.
To enable the function callbacks based on tag names, we need to invoke the parser with the "Subs" style. We also need to specify which namespace the function callbacks reside in, via the "Pkg" option:
|
This will cause a series of function callbacks based on the tags and the contents of the XML file. The start of a tag will invoke a function with the same name as the tag in the SubHandlers namespace. The contents of the tag will be handled by the char_handler function, and the end of the tag will invoke a function with the same name as the tag, with an "_" appended (for example, for the end of the tag symbol, the function SubHandlers::symbol_() will be called).
Our XML file will cause the following sequence of function calls:
|
Now, it is a simple matter to write the transformation functions. We can still perform simple substitutions:
|
which use the stock symbol, contained in the contents of the symbol tag, to insert an image of the same name in the resulting HTML page. We can also implement more complicated logic:
|
The first parameter passed to the function is a handle to the parser itself, followed by the name of the tag (element), optionally followed by the tag attributes as attribute_name, attribute_value pairs. In the above case we print a different label based on the type attribute of the price tag.
The full program is available as a separate listing. Running the program on our XML file produces much more attractive output. A sample looks like:
|
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
