Getting the value of an attribute in an XML document using XSL

519 views Asked by At

I'm trying to get the value of iWantToGetThis.jpg and put it into an <img> during my XSL transformation. This is how my xml is structures:

<article>
    <info>
        <mediaobject>
            <imageobject>
                <imagedata fileref='iWantToGetThis.jpg'>

Here's what I've come up with for the XSL:

<xsl:template name="user.header.content">
    <xsl:stylesheet xmlns:d='http://docbook.org/ns/docbook'>
        <img><xsl:attribute name="src">../icons/<xsl:value-of select='ancestor-or-self::d:article/info/mediaobject/imageobject/imagedata/@fileref' /></xsl:attribute></img>
    </xsl:stylesheet>
</xsl:template>

The image is being added to the output, but the src attribute is set to "../icons/", so I'm assuming it's not finding the fileref attribute in the XML. This looks perfectly valid to me, so I'm not sure what I'm missing.

1

There are 1 answers

3
Tim C On BEST ANSWER

I am not sure how you can get anything back at all, because that does not look like a valid XSLT document (I would expect the error "Keyword xsl:stylesheet may not contain img.").

However, it may be you are just showing a fragment of the code. If this is the case, your issue may be that you have only specified the namespace for the article element, when you really need to specify it for all elements in your xpath. Try this

<xsl:value-of 
   select="ancestor-or-self::d:article/d:info/d:mediaobject/d:imageobject/d:imagedata/@fileref"/>

Another possible problem may be because you are using the 'ancestor-or-self' xpath axis to find the attribute. This would only work if your current context was already on the article element, or one of its descendants.

As a side note, you can simplify the code by making use of Attribute Value Templates here

<img src="../icons/{ancestor-or-self::d:article/d:info/d:mediaobject/d:imageobject/d:imagedata/@fileref}" />