XSLT实现跨路径输出节点值及添加响应节点的技术求助
XSLT实现节点值迁移与提示信息添加
当然可以实现你的需求,你的原代码存在若干问题导致无法生成预期结果,以下是修正后的完整解决方案:
原代码问题梳理
- 输出方法错误设置为
text,但需要生成XML结构,应改为xml - 根模板闭合标签拼写错误:
<xst:template>应为<xsl:template> - 调用命名模板的语法错误:应使用
<xsl:call-template name="items"/>而非<xsl:call-templates select="items"/> - XSLT 1.0不支持
fn:matches函数,需用兼容方式判断字符串格式 - 定义的
information变量未输出,无法生成目标节点 Item1Information模板逻辑冗余,原输入无该节点,直接生成即可
修正后的XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <Root> <ItemsResponse> <xsl:call-template name="items"> <xsl:with-param name="item1s" select="//Root/Items/Item1/text()"/> </xsl:call-template> </ItemsResponse> </Root> </xsl:template> <xsl:template name="items"> <xsl:param name="item1s"/> <!-- 判断字符串是否仅包含字母:将所有字母替换为空,若结果为空则符合要求 --> <xsl:variable name="only-letters" select="translate($item1s, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', '')"/> <Item1><xsl:value-of select="$item1s"/></Item1> <!-- 如果存在非字母字符,输出提示信息 --> <xsl:if test="$only-letters != ''"> <Item1Information>Input Failed Format</Item1Information> </xsl:if> </xsl:template> </xsl:stylesheet>
代码关键说明
- 输出配置:设置
method="xml"并开启indent="yes",确保输出结构清晰的XML - 根模板:直接构建目标XML的顶层结构,调用命名模板并传入Item1的文本值
- 格式判断:使用
translate函数实现XSLT1.0兼容的字母校验,替代不支持的matches函数 - 条件输出:根据字符串格式判断结果,决定是否添加提示信息节点,逻辑简洁直接
测试结果
将你的输入请求传入修正后的XSLT,将得到预期输出:
<Root> <ItemsResponse> <Item1>Rambutan12</Item1> <Item1Information>Input Failed Format</Item1Information> </ItemsResponse> </Root>
内容的提问来源于stack exchange,提问作者Toshi Mario
相关产品推荐
相关产品推荐

