XSLT transformation not retaining the attributes

2019-06-14 14:52发布

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?

2条回答
爷、活的狠高调
2楼-- · 2019-06-14 15:07

Try this:

<xsl:template match="@src">
    <xsl:attribute name="src">
        <xsl:value-of select="replace(.,'/assets/rep/','/images/')"/>
    </xsl:attribute>
</xsl:template> 
查看更多
该账号已被封号
3楼-- · 2019-06-14 15:31

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!

查看更多
登录 后发表回答