我有一个包含 img 标签的 XML
<xml>
<img src="/path/to/file.jpg" orginalwidth="150" />
</xml>
我想要:
<img src="/paht/to/file.jpg" size=SIZE />
其中 SIZE 是 orginalsize 和 100px 中的最小值
最佳答案
这个转换:
<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="pmaxSize" select="100"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@orginalwidth">
<xsl:attribute name="size">
<xsl:value-of select=".*not(. > $pmaxSize) + $pmaxSize*(. > $pmaxSize)"/>
<xsl:text>px</xsl:text>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
在提供的 XML 文档上执行时:
<xml>
<img src="/path/to/file.jpg" orginalwidth="150" />
</xml>
产生想要的结果:
<xml>
<img src="/path/to/file.jpg" size="100px"/>
</xml>
应用于以下 XML 文档时:
<xml>
<img src="/path/to/file.jpg" orginalwidth="99" />
</xml>
结果又是想要的和正确的结果:
<xml>
<img src="/path/to/file.jpg" size="99px"/>
</xml>
解释:
在 XPath 1.0 中,任何 bool 值,当用作数字时,从 true()
转换为 1
,从 false()
转换为0
。
因此,表达式:
.*not(. > $pmaxSize) + $pmaxSize*(. > $pmaxSize)
如果 .
小于或等于 $pmaxSize
则计算为 .
,否则为 $pmaxSize
。
.
是解释为数字的当前节点的值。
关于xml - 使用 xsl 设置图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3882051/