tylik
tylik

Reputation: 1068

Put XML content in four HTML blocks

I have several XML tags which I want to place in four blocks (divs).

The input is the following:

<product>
  <product1>1</product1>
  <product2>2</product2>
  <product3>3</product3>
  <product4>4</product4>
  <product5>5</product5>
  <product6>6</product6>
  <product7>7</product7>
  <product8>8</product8>
</product>

The output I'm trying to have is:

<div><span>1</span> <span>5</span></div>
<div><span>2</span> <span>6</span></div>
<div><span>3</span> <span>7</span></div>
<div><span>4</span> <span>8</span></div>

Here is the link on the picture of what I am trying to have http://clip2net.com/s/1fON5

Tables won't be good here as I need four independent blocks.

Any help appreciated!

Upvotes: 0

Views: 91

Answers (1)

Tim C
Tim C

Reputation: 70628

Assuming you define a parameter called blocks, the first element within each block would be matched by simply doing the following:

<xsl:apply-templates select="product/*[position() &lt;= $blocks]" />

In the template that matches such the element, you then need to select the element itself, and then all following elements for the block (which will depend on the number of blocks) like so

<xsl:apply-templates
   select="self::*|following-sibling::*[position() mod $blocks = 0]"
   mode="block" />

Note the mode here is to stop the template recursively calling itself. In the matching template for this, you can add your code for the span tags in your case.

So, given the following XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes"/>
   <xsl:param name="blocks" select="4" />

   <xsl:template match="/">
      <xsl:apply-templates select="product/*[position() &lt;= $blocks]" />
   </xsl:template>

   <xsl:template match="product/*">
      <div>
      <xsl:apply-templates 
         select="self::*|following-sibling::*[position() mod $blocks = 0]" 
         mode="block" />
      </div>
   </xsl:template>

   <xsl:template match="*" mode="block">
      <span><xsl:value-of select="." /></span>
   </xsl:template>
</xsl:stylesheet>

When applied to your sample XML, the following is output:

<div><span>1</span><span>5</span></div>
<div><span>2</span><span>6</span></div>
<div><span>3</span><span>7</span></div>
<div><span>4</span><span>8</span></div>

Change the parameter to 3, and the following is output

<div><span>1</span><span>4</span><span>7</span></div>
<div><span>2</span><span>5</span><span>8</span></div>
<div><span>3</span><span>6</span></div>

Upvotes: 2

Related Questions