xmlxsltvalue-of

How to get value of XML element using XSL


I have a XML and XSL code, products have images and description. I want to append this images in description tag.

<images>
  <img_item type_name="">http://www.example.com.tr/ExampleData/example1.jpg</img_item>
  <img_item type_name="">http://www.example.com.tr/ExampleData/example2.jpg</img_item>
  <img_item type_name="">http://www.example.com.tr/ExampleData/example3.jpg</img_item>
</images>

I write XSL code like this (But it does not get value of img_type) :

      <Description>
        <xsl:for-each select="images/img_item">
          <xsl:text><![CDATA[<br/><img src="]]></xsl:text>
          <xsl:value-of select="images/img_item"/>
          <xsl:text><![CDATA[" />]]></xsl:text>
        </xsl:for-each>
      </Description>

My Code does not work. How can i get value of img_type (how can i get these links.)


Solution

  • The reason you are not getting and value is because are already positioned on the img_item, and your xsl:value-of select will be relative to that. So you just need to do this...

    <xsl:value-of select="." />
    

    Howver, you should avoid using CDATA to write out tags (unless you genuinely do want them to be escaped). Just write out the element you want directly

    <xsl:template match="/">
      <Description>
        <xsl:for-each select="images/img_item">
          <br />
          <img src="{.}" />
        </xsl:for-each>
      </Description>
    </xsl:template>
    

    Note the use of Attribute Value Templates to write out the src attribute value.