如果我的 XSL 文件中有以下元素:
<xsl:value-of select="replace(lower-case(@name), '_([a-z0-9])', '$1')" />
例如,从“get_polygene_lubricants”生成“getpolygenelubricants”。
我想做的是将'_'之后的第一个字母替换为 字母的大写变体。我用谷歌搜索,阅读文档, 但我没能在 XSLT 中找到任何解决方案 替换。
也许有人知道在 XSLT 2.0 中是否可行?
最佳答案
已编辑:根据原始发帖人的说明,下划线分隔的第一个字符串不应将其首字母大写。
这个解决方案不使用递归,应该更有效。
这是新的解决方案:
string-join(
(for $i in 1 to count(tokenize(.,'_')),
$s in tokenize(.,'_')[$i],
$fl in substring($s,1,1),
$tail in substring($s,2)
return
if($i eq 1)
then $s
else concat(upper-case($fl), $tail)
),
''
)
现在的结果完全符合要求:
underLinedString
下面是旧的解决方案。
replace() 函数假设您有一个固定的替换——因此它不是解决此问题的最佳工具。
这是一个单行 XPath 2.0 解决方案(它当然可以用作 XSLT 2.0 转换的一部分:) ):
string-join(
(for $s in tokenize(.,'_'),
$fl in substring($s,1,1),
$tail in substring($s,2)
return
concat(upper-case($fl), $tail)
),
''
)
当我们像这样在 XSLT 2.0 转换中使用上述表达式时:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:template match="/">
<xsl:sequence select=
"string-join(
(for $s in tokenize(.,'_'),
$fl in substring($s,1,1),
$tail in substring($s,2)
return
concat(upper-case($fl), $tail)
),
''
)
"/>
</xsl:template>
</xsl:stylesheet>
并将其应用于此 XML 文档:
<t>under_lined_String</t>
产生了想要的结果:
UnderLinedString
关于regex - XSLT 2.0,替换函数 : How to replace matched group with upper case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/489232/