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


Storing tag contents

In the earlier display-oriented applications, we only needed to output the tag contents. For our stock application, we need to access and store the contents of certain tags (such as price and volume) to compare them with the buy/sell criteria.

Our strategy for storing the contents of the tags using the stream-based processing model will be: prepare a storage place for the contents when the start of the tag is encountered, and store the contents of the tag via the char_handler function. Since the document is processed as a stream, first the start tag will be encountered, allowing us to set the stage for the storage of the contents. Next the contents of the tag will be encountered, and stored in their prepared location. Finally the end of the tag will be encountered, allowing any necessary cleanup and closeup of the storage location.

The storage location will be set up in the tag start function, and closed in the tag end function:



sub volume {
$::state::store_contents = "volume";
}

sub volume_ {
undef $::state::store_contents;
}

volume defines the store_contents variable, setting the storage location for the contents of the tag. volume_ subsequently undefines store_contents, making sure contents of other tags do not get stored in the same location.

char_handler needs to be modified to allow storage of the contents:



sub char_handler {
my ($p, $data) = @_;
if ($::state::store_contents) {
$::state::storage{$::state::store_contents} .= $data;
}
}

This checks if the variable store_contents is defined, and, if so, stores the data in the storage hash. The ::state namespace is used to separate the storage and state variables from the parser and handler namespaces.

Using this technique we can store the contents of the tags we are interested in. In the case of the price tag, the values of interest are expressed as attributes of the tag. We can store these as we encounter them:



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

# Read the attributes
while (@_) {
my $att = shift;
my $val = shift;
$attr{$att} = $val;
}

if ($attr{'type'} eq "ask") {
$::state::storage{'price'} = $attr{'value'};
}
}


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