Looking Ahead
In the previous chapter (Day 14) we discussed the disadvantage of the event driven approach; it is not possible to make decisions based on information that comes later in the data stream.
Let's take following piece of XML.
Listing 15.12 A Piece of XML to be Converted
1: <cities id="L5"> 2: <city>Amsterdam</city> 3: <city>Paris</city> 4: <city>Toronto</city> 5: <city>Vancouver</city> 6: <city>Brussels</city> 7: </cities>
| I would like to translate the previous XML fragment to the following piece of HTML: |
<p>City 1 of 5<BR>
Amsterdam</p>
<p>City 2 of 5<BR>
Paris</p>
...
| In the data stream, when we arrive at the city Amsterdam we can test to know its position, but it is not possible to know at that point that there are 5 cities mentioned in total. |
To solve this, Omnimark uses referents.
| A referent outputs a value to be determined at some other point of processing, most of the time later on in the data stream. |
By using referents you are able to stick placeholders in your output. Later on you can assign or change their values, as shown in Listing 15.13.
Listing 15.13 nrofcities.xom-Using Referents
1: global counter nrofcities initial {0} ; a variable with
name "nrofcities" and value "0"
2:
3: element cities ;rule
4: output "%c" ; continue parsing
5:
6: element city
7: increment nrofcities ; the variable "profcities"
is incremented (+1)
8: output "<p>"
9: output "City %d(nrofcities) of " ; the value of
variable "nrofcities" is sent to the output
10: output referent "totalofcities"
11: ; the referent is the placeholder for the
not known yet value of the total of cities
12: ; the content of the placeholder is sent to
the output
13: output "<BR>"
14: output "%c"
15: output "</p>"
16: set referent "totalofcities" to "%d(nrofcities)"
17: ; the value of "nrofcities" is placed in
the placeholder
18: ; after the first its 1, then 2, and
finally for our example 5
| On line 1 we declare a variable named nrofcities. The initial value is set to 0. |
On line 3 we have our element rule for the element cities. The action defined here is continue parsing.
On line 6 we define our element rule for the element city. First we increment our variable nrofcities. For Amsterdam the value will be 1, 2 for Paris, and so on. On line 8 we start writing to the output: <p>City followed by the current value of the variable nrofcities, followed by of, followed by the placeholder totalofcities, which we don't yet know the value for.
On line 16 the value of the placeholder totalofcities is set to the value of nrofcities. This means that after processing the file the value of totalofcities will be 5.
Because we have been using referents, a second pass/run of the file is needed. It is during this second pass that the placeholder is replaced by its final value.
|