Repeating structures

When creating tabular output from source elements, or some other very regular structure, a technique is available that reduces the number of templates needed, and in so doing improves the clarity of the stylesheet. For example, consider the need to transform the following structure into a tabular format:

<countries>
  <country>
    <name>United Kingdom</name>
    <capital>london</capital>
  </country>
  <country>
    <name>United States</name>
    <capital>Washington</capital>
    <borders>Canada</borders>
    <borders>Mexico</borders>
  </country>
</countries>

To create an HTML table for this data, with one row for each country, the following four templates could be defined:

<template match="countries">
  <html:TABLE><apply-templates/></html:TABLE>
</template>

<template match="country">
  <html:TR><apply-templates/></html:TR>
</template>

<template match="name">
  <html:TH><apply-templates/></html:TH>
</template>

<template match="capital | borders">
  <html:TD><apply-templates/></html:TD>
</template>

It would require some study to deduce the exact nature of the conversion to be applied. To clarify this example, the output would be as follows:

<TABLE>
  <TR><TH>United Kingdom</TH>
      <TD>London</TD>
  </TR>
  <TR><TH>United States</TH>
      <TD>Washington</TD>
      <TD>Canada</TD>
      <TD>Mexico</TD>
  </TR>
</TABLE>

Using the For Each element, the entire transformation can be accomplished with a single template. The Select attribute applies the enclosed template to each occurrence of the matching element. This mechanism is particularly useful when there are multiple levels of structures, as in the variable number of bordering countries in this example:

<template match="countries">
  <html:TABLE>
  <for-each select="country">
    <html:TR>
    <html:TH><apply-templates select="name"/></html:TH>
    <html:TD><apply-templates select="capital"/>
    </html:TD>
    <for-each select="borders">
      <html:TD><apply-templates/></html:TD>
    </for-each>
    </html:TR>
  </for-each>
  </html:TABLE>
</template>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.125.219