urlxsltabsolute-pathrelative-url

XSLT append URL from relative to absolute


In my XML document, I am pulling the content of a <TextBlock> that contains images. The XML shows:

<img src="/templates_soft/images/facebook.png" alt="twitter" />

When I view the page, the image doesn't show up because it is not at the same path as the original page.

I need to add the rest of the URL for the images to display. Something like http://www.mypage.com/ so that the image displays from http://www.mypage.com/templates_soft/images/facebook.png

Is there a way to do this?


Solution

  • Use:

    <img src="{$imageBase/}templates_soft/images/facebook.png" alt="twitter" />
    

    where the xsl:variable named $imageBase is defined to contain the necessary prefix (in your case "http://www.mypage.com").

    Here is a complete XSLT solution:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:param name="pimageBase" select="'http://www.mypage.com'"/>
    
        <xsl:template match="img">
       <img src="{concat($pimageBase, @src)}" alt="{@alt}"/>
      </xsl:template>
    </xsl:stylesheet>
    

    when this transformation is applied on the following XML document:

    <img src="/templates_soft/images/facebook.png" alt="twitter" />
    

    the wanted, correct result is produced:

    <img src="http://www.mypage.com/templates_soft/images/facebook.png" alt="twitter"/>