Xml – How to add an image



I have a simple XML document that contains image information. I need to transform it into HTML. However, I can't see where the open tag is and when I use the XSL code below, it shows the following error message:

"Cannot write an attribute node when no element start tag is open."

XML content:

        <HeaderText>Dan Testing</HeaderText>
        <img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/>
        <p>This is a test of the body text<br  /></p>

XSL code:

<xsl:stylesheet version="1.0" extension-element-prefixes="msxsl"
    exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    <xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/>
    <xsl:template match="/" xml:space="preserve">
            <xsl:attribute name="width">
            <xsl:attribute name="height">
            <xsl:attribute name="class">
            <xsl:attribute name="src">
                <xsl:copy-of select="/root/Image/node()"/>

Best Solution

Just to clarify the problem here - the error is in the following bit of code:

<xsl:attribute name="src">
    <xsl:copy-of select="/root/Image/node()"/>

The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).

A MUCH shorter solution (and perhaps more elegant) would be the following:

<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>

The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.

Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.

Related Question