Awadesh
Awadesh

Reputation: 1

Displaying an image using XML and XSLT

My XML is like below:

<?xml version="1.0" encoding="ISO-8859-1"?>    
<chapter id="ch01">
    <sect1>
        <title>Wattage</title>
        <para>Paragraph1</para>
        <para>Paragraph2</para>
        <para><figure>
                <caption>
                    <para>
                    <i>Sample image caption</i></para>
                </caption>
                <img src="myimagepath\cover_front.jpg"/>
            </figure>
        </para>
    </sect1>
</chapter>

I am having issues in displaying image on the HTML page where I am rendering my XML using XSLT (through C# aspx page).

My XSLT is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html> 
            <body>
                <h2>My Book</h2>
                <xsl:apply-templates select="chapter/sect1" />
            </body>
        </html>
    </xsl:template>
    <xsl:template match="chapter/sect1">
        <xsl:apply-templates select="title" />
        <xsl:apply-templates select="para/figure" />
        <br />
    </xsl:template>
    <xsl:template match="title">
        <b><span style="font-size=22px;">
                <xsl:value-of select="." />
            </span>
        </b>
        <br />
    </xsl:template>
    <xsl:template match="para/figure">
        <xsl:element name="img">
            <xsl:attribute name="src">
                <xsl:value-of select="." />
            </xsl:attribute>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

My Image is not displaying using above XSLT. Can anyone please help. I am new to XSLT.

Upvotes: 0

Views: 2465

Answers (1)

Murph
Murph

Reputation: 10190

The point where you're rendering para/figure isn't doing quite what you think, the point at which you select "." for the image source should in fact render all of:

<caption><para><i>Sample image caption</i></para></caption>
<img src="myimagepath\cover_front.jpg"/>

Try changing this template: to:

<xsl:template match="para/figure">
    <img src="{img/@src}" />
</xsl:template>

(that's working from memory) so:

  • para/figure has two child elements caption and img
  • So we want to output a tag "img" (that the name is the same is incidental) with an attribute "src" (again incidental) and we want the src to be the src attribute (@ == attribute) of the img element of the current node. The curly braces enable magic to put the value in inline in the tag you're rendering out.

Upvotes: 1

Related Questions