You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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>&#xa;</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>&#xa;</xsl:text>
</xsl:template>

内容的提问来源于stack exchange,提问作者Ulf Tietze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:45:04