XSLT 转换不保留属性 [英] XSLT transformation not retaining the attributes

查看:37
本文介绍了XSLT 转换不保留属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下 XML 需要查找和替换 src 属性参数中的路径

<ul><字体>测试示例字体测试</font><img src="/assets/rep/myimage.png">测试<img src="/assets/rep/myimage.png" height="20px">测试

我的XSLT如下

<img src="{$imagesrc}"/></xsl:模板></xsl:stylesheet>

XSLT 再现适用于

测试

但不是为了

测试

我尝试添加 match="@src[parent::img]" 但这也不起作用.您能否让我知道我在 XSLT 中缺少什么以保留属性并仅修改src"属性?

解决方案

将您当前的逻辑更改为这样的模板:

<预><代码>...<xsl:template match="img"><xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy></xsl:模板><xsl:template match="img/@src"><xsl:attribute name="src"><xsl:value-of select="replace(.,'/assets/rep/','/images/')"/></xsl:attribute></xsl:模板>...

在您的尝试中,您创建了一个元素 而您的上下文节点是一个属性 @src.使用提供的示例,您会没事的!

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?

解决方案

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!

这篇关于XSLT 转换不保留属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆