如何在XSLT 1.0中将斜杠分隔字符串转为带双引号的逗号分隔串
在XSLT 1.0中实现斜杠分隔字符串的格式转换
可以实现。由于XSLT 1.0没有内置的字符串拆分函数,我们可以通过递归模板来处理斜杠分隔的字符串,将其转换为每个元素用双引号包裹、逗号分隔的格式。
以下是完整的XSLT实现代码:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://xmlns.oracle.com/Application1/Project1/BPELProcess1" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <!-- 匹配根节点,生成响应结构 --> <xsl:template match="/"> <ns0:processResponse> <ns0:result> <!-- 调用递归模板处理input节点的文本 --> <xsl:call-template name="split-and-wrap"> <xsl:with-param name="text" select="/ns0:process/ns0:input/text()"/> </xsl:call-template> </ns0:result> </ns0:processResponse> </xsl:template> <!-- 递归拆分字符串的核心模板 --> <xsl:template name="split-and-wrap"> <xsl:param name="text"/> <xsl:param name="delimiter" select="'/'"/> <xsl:choose> <!-- 如果字符串中还有分隔符,拆分出第一个元素并包裹双引号 --> <xsl:when test="contains($text, $delimiter)"> <xsl:text>"</xsl:text> <xsl:value-of select="substring-before($text, $delimiter)"/> <xsl:text>",</xsl:text> <!-- 递归处理剩余的字符串 --> <xsl:call-template name="split-and-wrap"> <xsl:with-param name="text" select="substring-after($text, $delimiter)"/> </xsl:call-template> </xsl:when> <!-- 处理最后一个元素,包裹双引号(避免末尾多余逗号) --> <xsl:otherwise> <xsl:text>"</xsl:text> <xsl:value-of select="$text"/> <xsl:text>"</xsl:text> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
代码说明:
- 命名空间处理:提前声明输入输出所需的命名空间,确保生成的XML结构符合要求。
- 递归模板
split-and-wrap:- 使用
contains检查字符串中是否还有斜杠分隔符。 - 用
substring-before提取第一个分隔符前的内容,包裹双引号后追加逗号。 - 用
substring-after获取剩余字符串,递归调用自身继续处理。 - 当没有分隔符时,处理最后一个元素,仅包裹双引号,避免末尾出现多余逗号。
- 使用
- 根节点匹配:生成指定的
processResponse结构,并调用递归模板处理input节点的文本内容。
将上述XSLT应用到你提供的输入XML后,会生成符合要求的输出结果。
内容的提问来源于stack exchange,提问作者sum
相关产品推荐
相关产品推荐

