XSLT append URL from relative to absolute
-
12-10-2019 - |
Question
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"/>
OTHER TIPS
If you go with XSLT, you simply create an XML that contains the entire URL as you desire, you then tag the XSLT up so it contains the "pointers" to the original fields in the XML file. If you are binding to a control, like a Grid, you can row bind and add the information at that point, if it is easier for you to do than XSLT.