【问题标题】:XSLT 3.0 - Not able to get Array of objects in XSLT 3.0 xml-to-json()XSLT 3.0 - 无法在 XSLT 3.0 xml-to-json() 中获取对象数组
【发布时间】:2021-11-08 19:25:58
【问题描述】:

我正在尝试使用 XSLT 3.0 将给定的 json 数据从一种形式转换为另一种形式。我正在使用 XSLT 3.0 提供的 json-to-xml 和 xml-to-json 函数将数据从 .to json 转换为 xml。

我有以下 json 数据。

 {
   "id": "123456",
   "result": "Success"
  }

我正在尝试使用 XSLT 3.0 将其转换为以下形式

[
  {
   "key":"id",
   "value":"123456"
  },
  {
    "key":"result",
    "value":"Success"
   }
 ]

我有以下 XSLT。

<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">
     <map>
      <xsl:apply-templates select="$json-xml//map"/>
     </map>
    </xsl:variable>
    <xsl:value-of select="xml-to-json($transformed-json-xml, map { 'indent' : true() })"/>
   </xsl:template>

    <xsl:template match="map[string[@key = 'id'] and string[@key = 'result']]">
    <string key="key">id</string>
    <string key="value">{string[@key = 'id']}</string>
    </xsl:template>

   </xsl:stylesheet>

但它只产生一个对象

 { "key" : "id",
"value" : "123456" }

谁能指出我需要修改的地方?

【问题讨论】:

    标签: java xml xslt xslt-3.0 xml-to-json


    【解决方案1】:

    好吧,如果你想要一个数组作为你需要改变的外部 JSON 结构

    <xsl:variable name="transformed-json-xml">
     <map>
      <xsl:apply-templates select="$json-xml//map"/>
     </map>
    

    <xsl:variable name="transformed-json-xml">
     <array>
      <xsl:apply-templates select="$json-xml//map"/>
     </array>
    

    你想要的地图

    <xsl:template match="map[string[@key = 'id'] and string[@key = 'result']]">
      <xsl:apply-templates/>
    </xsl:template>
    

      <xsl:template match="string">
        <map>
          <string key="key">{@key}</string>
          <string key="value">{.}</string>
        </map>
      </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2020-12-21
      相关资源
      最近更新 更多