Ope*_*lex 10 string xslt pascalcasing string-formatting
我正在尝试在XSLT中格式化字符串,这些字符串需要处于pascal情况下才能正确地用于我正在使用的应用程序.
例如:
this_text将成为ThisText
this_long_text将成为ThisLongText
是否有可能将其设置在我可以向格式发送输入的位置,以便我不必多次重新创建格式?
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vLower" select=
"'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="vUpper" select=
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:call-template name="Pascalize">
<xsl:with-param name="pText" select="concat(., '_')"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="Pascalize">
<xsl:param name="pText"/>
<xsl:if test="$pText">
<xsl:value-of select=
"translate(substring($pText,1,1), $vLower, $vUpper)"/>
<xsl:value-of select="substring-before(substring($pText,2), '_')"/>
<xsl:call-template name="Pascalize">
<xsl:with-param name="pText"
select="substring-after(substring($pText,2), '_')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
应用于此XML文档时:
<t>
<a>this_text</a>
<b>this_long_text</b>
</t>
Run Code Online (Sandbox Code Playgroud)
产生预期的结果:
<t>
<a>ThisText</a>
<b>ThisLongText</b>
</t>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是camelCase,这是PascalCase
小智 6
事实上,两年之后,这是一个XSLT 2.0解决方案:
<xsl:function name="fn:pascal-case">
<xsl:param name="string"/>
<xsl:value-of select="string-join(for $s in tokenize($string,'\W+') return concat(upper-case(substring($s,1,1)),substring($s,2)),'')"/>
</xsl:function>
Run Code Online (Sandbox Code Playgroud)
它会将'this_long_text'或'this-long-text'传递给'ThisLongText',因为它会破坏任何非单词字符.
在我最熟悉的正则表达式中(perl,pcre等),下划线被认为是'\ w'字符类的一部分(因此不是\ W的一部分),但是对于XSLT 2.0,使用了XSD数据类型( http://www.w3.org/TR/xmlschema-2/)和'\ w'定义为:
[#x0000-#x10FFFF]-[\p{P}\p{Z}\p{C}] (all characters except the set of "punctuation", "separator" and "other" characters)
Run Code Online (Sandbox Code Playgroud)
所以'\ W'包含一个下划线.