Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add xsl attribute

I have an xml with img tag

<img>
source
</img>

I want to generate:

<img src="source.jpg">

I tried something like that:

<img>
<xsl:attribute name="src">
  <xsl:text>
        <xsl:value-of select="node()" />.jpg
      </xsl:text>
    </xsl:attribute>
</img> 

but it doesng work

like image 872
liysd Avatar asked Dec 22 '22 00:12

liysd


2 Answers

Use:

<img src="{normalize-space()}.jpg"/>

This assumes the <img> element is the current node.

like image 190
Dimitre Novatchev Avatar answered Jan 05 '23 22:01

Dimitre Novatchev


The reason why what you are doing does not work is that you cannot evaluate XSLT expressions inside of the <xsl:text> element.

<xsl:text> can only contain literal text, entity references, and #PCDATA.

If you move the <xsl:value-of> outside of the <xsl:text>, then the following will work:

    <img>
        <xsl:attribute name="src">
            <xsl:value-of select="node()" />
            <xsl:text>.jpg</xsl:text>
        </xsl:attribute>
    </img>

However, selecting <xsl:value-of select="node()> for the <img> in your example will include the carriage returns and whitespace characters inside of the <img> element, which is probably not what you want in your src attribute value.

That is why Dimitre Novatchev used normalize-space() in his answer. Applying that to the example above:

    <img>
        <xsl:attribute name="src">
            <xsl:value-of select="normalize-space(node())" />
            <xsl:text>.jpg</xsl:text>
        </xsl:attribute>
    </img>

If you get rid of the <xsl:text> as Fabiano's solution suggests, then you could also do this:

    <img>
        <xsl:attribute name="src"><xsl:value-of select="normalize-space(node())" />.jpg</xsl:attribute>
    </img> 
like image 38
Mads Hansen Avatar answered Jan 05 '23 23:01

Mads Hansen