如何使用XSLT从包含mixed content的XML元素中提取完整文本
你现有代码的核心问题是只显式处理了important元素的前置兄弟文本、以及important元素本身,完全遗漏了important元素之后的文本节点,也没有正确遍历description下的所有子节点。
根据你的需求可以选择对应解决方案:
场景1:需要保留important标签转<span>的结构
调整模板如下,新增通用文本节点处理规则,直接遍历description下的所有子节点即可:
<xsl:template match="description" mode="important_recursive"> <xsl:apply-templates select="node()" mode="important_recursive"/> <!-- 每个description输出后添加换行,匹配预期的输出格式 --> <xsl:text>
</xsl:text> </xsl:template> <xsl:template match="important" mode="important_recursive"> <span><xsl:value-of select="."/></span> </xsl:template> <!-- 新增文本节点默认处理规则,直接输出文本内容 --> <xsl:template match="text()" mode="important_recursive"> <xsl:value-of select="."/> </xsl:template>
这个写法会按节点顺序依次处理description下的所有内容:普通文本直接输出,important元素转成span包裹内容输出,自动拼接成完整的内容。
场景2:仅需要纯文本内容,不需要span标签
逻辑可以大幅简化,直接取description的字符串值即可,XSLT会自动拼接所有后代文本节点:
<xsl:template match="description" mode="important_recursive"> <xsl:value-of select="."/> <xsl:text>
</xsl:text> </xsl:template>
内容的提问来源于stack exchange,提问作者Ulf Tietze
相关产品推荐
相关产品推荐

