如何用XSLT将元素内的JSON替换为纯文本?
解决方案:用XSLT替换JSON内容为纯文本
可行性:完全可以实现
你可以通过XSLT的字符串处理逻辑,或是XSLT 3.0的内置JSON解析功能,将元素内的JSON内容替换为指定的纯文本(比如示例中的Probable Cause)。
两种实现方案
方案1:XSLT 1.0/2.0(字符串截取)
如果使用较低版本的XSLT(无内置JSON支持),可以针对固定格式的JSON用字符串函数提取目标值:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:company="http://example.com/company" xmlns:j="http://example.com/j" xmlns:s="http://example.com/s" xmlns:nc="http://example.com/nc"> <!-- 默认复制所有节点结构 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配所有包含目标JSON的文本节点 --> <xsl:template match="nc:DescriptionText/text() | j:Name/text() | j:DescriptionText/text()"> <!-- 提取description字段的值 --> <xsl:variable name="desc-fragment" select='substring-after(., ""description":"")'/> <xsl:value-of select='substring-before($desc-fragment, ""}")'/> </xsl:template> </xsl:stylesheet>
注意:这种方式仅适用于JSON格式固定的场景,若JSON键的顺序或结构变化,可能失效。
方案2:XSLT 3.0(内置JSON解析)
XSLT 3.0提供了parse-json()内置函数,可直接将JSON字符串解析为XSLT映射(map),更健壮灵活:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:company="http://example.com/company" xmlns:j="http://example.com/j" xmlns:s="http://example.com/s" xmlns:nc="http://example.com/nc"> <!-- 默认复制所有节点结构 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配所有包含目标JSON的文本节点 --> <xsl:template match="nc:DescriptionText/text() | j:Name/text() | j:DescriptionText/text()"> <!-- 解析JSON并提取description字段 --> <xsl:variable name="json-data" select="parse-json(.)"/> <xsl:value-of select="$json-data?description"/> </xsl:template> </xsl:stylesheet>
这种方案不受JSON键顺序影响,只要JSON格式合法就能正确提取值,但需要你的XSLT处理器支持XSLT 3.0(比如Saxon系列处理器)。
关键结论
- XSLT 3.0内置原生JSON解析功能,是处理这类需求的最优选择;
- 低版本XSLT可通过字符串处理实现,适合固定格式的JSON场景;
- 只需在现有XSLT中添加对应模板,即可实现实时替换。
内容的提问来源于stack exchange,提问作者StealthRT
相关产品推荐
相关产品推荐

