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

如何修改XSLT代码,直接使用JSON源文档而非参数完成转换?

问题描述

原本可通过参数input传入JSON文件名来运行这段XSLT代码,但基础设施不允许该方式,会将输入作为源文档处理。需要修改模板,使其直接使用源文档(而非参数)且不报错。

原代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:math="http://www.w3.org/2005/xpath-functions/math"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xpath-default-namespace="http://www.w3.org/2005/xpath-functions"
  exclude-result-prefixes="xs math" version="3.0">

 <xsl:mode on-no-match="shallow-copy"/>

 <xsl:param name="input"/>

 <xsl:output method="text"/>

 <xsl:template name="xsl:initial-template">
    <xsl:variable name="input-as-xml" select="json-to-xml(unparsedtext($input))"/>
    <xsl:variable name="transformed-xml" as="document-node()">
       <xsl:apply-templates select="$input-as-xml"/>
    </xsl:variable>
    <xsl:value-of select="xml-to-json($transformed-xml)"/>
 </xsl:template>

 <xsl:template match="map[array[@key='tags']/string='ice']/number[@key='price']/text()">
    <xsl:value-of select="xs:decimal(.)*1.1"/>
 </xsl:template>
</xsl:stylesheet>

修改方案

修改后的代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:math="http://www.w3.org/2005/xpath-functions/math"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xpath-default-namespace="http://www.w3.org/2005/xpath-functions"
  exclude-result-prefixes="xs math" version="3.0">

 <xsl:mode on-no-match="shallow-copy"/>

 <xsl:output method="text"/>

 <xsl:template name="xsl:initial-template">
    <!-- 直接将源文档的文本内容转换为JSON对应的XML结构 -->
    <xsl:variable name="input-as-xml" select="json-to-xml(/)"/>
    <xsl:variable name="transformed-xml" as="document-node()">
       <xsl:apply-templates select="$input-as-xml"/>
    </xsl:variable>
    <xsl:value-of select="xml-to-json($transformed-xml)"/>
 </xsl:template>

 <xsl:template match="map[array[@key='tags']/string='ice']/number[@key='price']/text()">
    <xsl:value-of select="xs:decimal(.)*1.1"/>
 </xsl:template>
</xsl:stylesheet>

核心修改说明

  • 移除xsl:param name="input"参数,不再依赖外部传入文件名。
  • 将json-to-xml(unparsedtext($input))替换为json-to-xml(/):/代表源文档的根节点,若输入是纯JSON文本,处理器会将其视为单个文本节点,/会直接选中该文本内容并传入json-to-xml()完成转换。
  • 若处理器将源文档解析为带有包裹节点的XML(例如<root>...</root>包含JSON文本),可调整为json-to-xml(/text())来精准提取文本内容。

内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:02:52