无法使用XSLT转换XML提取仅带属性的Question标签
问题根因
你当前使用的<xsl:copy-of>会完整复制匹配到的Question节点的全部内容,包括子节点、后代节点,所以会把不需要的QuestionText、Answer等标签也一起输出。
解决方案
有两种实现方式可以仅保留Question标签和其属性:
方案1:直接遍历构造(简单快速)
直接替换原来的<xsl:copy-of>代码段即可,无需额外新增模板:
把你代码里的
<xsl:copy-of select="tal:Upsert/tal:Question"></xsl:copy-of>
替换为:
<xsl:for-each select="tal:Upsert/tal:Question"> <!-- 仅复制Question节点本身 --> <xsl:copy> <!-- 复制Question的所有属性 --> <xsl:copy-of select="@*"/> </xsl:copy> </xsl:for-each>
方案2:新增专用模板(扩展性更好)
如果后续还有其他节点需要类似处理,或者需要对Question做更多自定义逻辑,更推荐用模板匹配的方式:
- 在
<xsl:stylesheet>下新增一个匹配tal:Question的专属模板:
<xsl:template match="tal:Question"> <xsl:copy> <xsl:copy-of select="@*"/> </xsl:copy> </xsl:template>
- 把原来的
<xsl:copy-of>替换为模板调用:
<xsl:apply-templates select="tal:Upsert/tal:Question"/>
完整修改后的XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://ns.hr-xml.org/2007-04-15" xmlns:hr="http://ns.hr-xml.org/2007-04-15" xmlns:tal="http://talemetry.com/" exclude-result-prefixes="tal"> <!-- 新增Question专属匹配模板 --> <xsl:template match="tal:Question"> <xsl:copy> <xsl:copy-of select="@*"/> </xsl:copy> </xsl:template> <xsl:template match="/"> <SOAP-ENV:Envelope xmlns="" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Header> <AuthHeader xmlns="http://talemetry.com/"> <Username>${param_cred_api_client_id}</Username> <Password>${param_cred_api_client_secret}</Password> </AuthHeader> </SOAP-ENV:Header> <SOAP-ENV:Body> <Delete xmlns="http://talemetry.com/"> <Locale> <xsl:value-of select="tal:Upsert/tal:Locale"/> </Locale> <LanguageAware>true</LanguageAware> <!-- 调用模板输出Question --> <xsl:apply-templates select="tal:Upsert/tal:Question"/> </Delete> </SOAP-ENV:Body> </SOAP-ENV:Envelope> </xsl:template> </xsl:stylesheet>
内容的提问来源于stack exchange,提问作者Dark Matter
相关产品推荐
相关产品推荐

