Repeating a block of TAGs in XML using XSLT
I have another query, which I tried but can't get it done... Below is the XML Code -
<Main>
<Region>
<Division>
<DivName>Abc</DivName>
<Desc>BBB</Desc>
<Info></Info>
</Division>
<Division>
<DivName>Pqr</DivName>
<Desc></Desc>
<Info></Info>
</Division>
<Division>
.
.
.
</Division>
</Region>
</Main>
In the Division tag, DivName is compulsory, ie; it will be there, but Desc and Info are optional. Also the Division tag, which contains Desc, DivName and Info tags, could appear only once of number of times. So to display it, I must use for-each.
I also want line breaks between these tags. Till now I tried a little with failure. The HTML output, I want is
<b>DivName Text</b>
<p>Desc Text, if any</p>
<p>Info Text, if any</p>
<hr/>
<b>DivName Text</b>
<p>Desc Text, if any</p>
<p>Info Text, if any</p>
Thanks in advance.. 开发者_如何学JAVAHave a nice day John
This simple transformation (no <xsl:for-each>
and no conditionals):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="Division[position() >1]">
<hr />
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="Division/*[text()]">
<p><xsl:value-of select="."/></p>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<Main>
<Region>
<Division>
<DivName>Abc</DivName>
<Desc>BBB</Desc>
<Info>More info abour Abc</Info>
</Division>
<Division>
<DivName>Pqr</DivName>
<Desc>Pqr desc.</Desc>
<Info>More info abour Pqr</Info>
</Division>
</Region>
</Main>
produces the wanted, correct result:
<p>Abc</p>
<p>BBB</p>
<p>More info abour Abc</p>
<hr/>
<p>Pqr</p>
<p>Pqr desc.</p>
<p>More info abour Pqr</p>
And it is displayed by the browser as:
Abc
BBB
More info abour Abc
Pqr
Pqr desc.
More info abour Pqr
How about this:
<xsl:for-each select="Division">
<xsl:if test="position() != 1">
<hr/>
</xsl:if>
<p><xsl:value-of select="DivName" /></p>
<xsl:if test="Desc">
<p><xsl:value-of select="Desc"/></p>
</xsl:if>
<xsl:if test="Info">
<p><xsl:value-of select="Info"/></p>
</xsl:if>
</xsl:for-each>
精彩评论