XSLT 3.0使用xml-to-json()无法输出对象数组问题求助
你当前的代码存在两个核心问题:一是最终输出的结构是对象而非你需要的数组,二是模板只处理了id单个字段,没有遍历原JSON的所有属性。
修改后的完整代码如下:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="3.0" xmlns="http://www.w3.org/2005/xpath-functions" xpath-default-namespace="http://www.w3.org/2005/xpath-functions" expand-text="yes"> <xsl:param name="json"/> <xsl:output method="text"/> <xsl:mode on-no-match="shallow-skip"/> <xsl:template match="/" name="init"> <xsl:variable name="json-xml" select="json-to-xml($json)"/> <xsl:variable name="transformed-json-xml"> <!-- 改成array标签,对应JSON数组 --> <array> <!-- 遍历原map下的所有属性节点 --> <xsl:apply-templates select="$json-xml//map/*"/> </array> </xsl:variable> <xsl:value-of select="xml-to-json($transformed-json-xml, map { 'indent' : true() })"/> </xsl:template> <!-- 匹配原map下的每个属性节点,每个生成一个key-value对象 --> <xsl:template match="map/*"> <map> <string key="key">{@key}</string> <string key="value">{.}</string> </map> </xsl:template> </xsl:stylesheet>
改动说明:
- 把
transformed-json-xml里的外层<map>标签换成<array>:XSLT的xml-to-json函数会把<array>标签转换为JSON数组,符合你要的输出结构。 - 修改
apply-templates的选择路径为$json-xml//map/*:遍历原JSON对象下的所有属性,而非只处理整个map节点。 - 重写匹配模板:匹配每个属性节点,为每个节点生成一个包含
key和value字段的<map>(对应JSON对象),自动读取原属性的键名和值,不需要硬编码字段名。
修改后运行即可得到你需要的对象数组输出。
内容的提问来源于stack exchange,提问作者ved g
相关产品推荐
相关产品推荐

