问题
We have the following XML that we need to find and replace the path in src attribute parameters
<?xml version="1.0"?>
<ul>
<font> test sample font test </font>
<img src="/assets/rep/myimage.png"> test</img>
<img src="/assets/rep/myimage.png" height="20px"> test</img>
</ul>
My XSLT is as follows
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- remove disallowed elements but keep its children -->
<xsl:template match="font">
<xsl:apply-templates></xsl:apply-templates>
</xsl:template>
<xsl:template match="@src">
<xsl:variable name="imagesrc" select="replace(.,'/assets/rep/','/images/')"/>
<img src="{$imagesrc}" />
</xsl:template>
</xsl:stylesheet>
The XSLT rendition works for
<img src="/assets/rep/myimage.png"> test</img>
but not for
<img src="/assets/rep/myimage.png" height="20px"> test</img>
I tried to add match="@src[parent::img]" but that does not work either. Can you let me know what I am missing in my XSLT to retain the attributes and ONLY modify "src" attributes?
回答1:
Change your current logic to templates like this:
...
<xsl:template match="img">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="img/@src">
<xsl:attribute name="src">
<xsl:value-of select="replace(.,'/assets/rep/','/images/')"/>
</xsl:attribute>
</xsl:template>
...
In your try, you created an element <img>
while your context-node is an attribute @src
. With the provided example you will be fine!
回答2:
Try this:
<xsl:template match="@src">
<xsl:attribute name="src">
<xsl:value-of select="replace(.,'/assets/rep/','/images/')"/>
</xsl:attribute>
</xsl:template>
来源:https://stackoverflow.com/questions/47797073/xslt-transformation-not-retaining-the-attributes