转换使用函数 "parse-json" returns 错误

Transforming using function "parse-json" returns error

我正在尝试使用函数“parse-json”直接处理 JSON 数据。 我已经检查了 JSON 所以它的语法是正确的。在元素中添加文本值而不是查询 JSON 数据,生成结果但不使用 JSON 数据。

JSON数据:

<data>
{
    "general": {
      "Language": "English",
      "Country": "Sweden"
    },

    "units-definitions": {
      "SEK": "42B"
    }
  }
</data>

XSL:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:root="http://www.example.org/1"
  xmlns:flat="http://www.example.org/2"
  exclude-result-prefixes="xs"
  expand-text="yes">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="data">
    <root:report>
      <xsl:variable name="json" select="parse-json(.)"/>

      <!-- These works -->
      <!-- <flat:Country>1</flat:Country>
      <flat:SEK>2</flat:SEK> -->

      <!-- These does not work -->
      <flat:Country>{?general?Country}</flat:Country>
      <flat:SEK>{?units-definitions?SEK}</flat:SEK>

    </root:report>
</xsl:template>

</xsl:transform>

结果

空白输出

可见错误:

Saxon-HE 10.5J from Saxonica
Java version 11.0.11
Error at char 1 (on line 22) of file:[Xxx.xsl] 
  XPTY0004  The left-hand operand of '?' must be a map or an array; the supplied expression
  is of type element(Q{}data)
Errors were reported during stylesheet compilation
[Finished in 0.828s]

预期结果:

<?xml version="1.0" encoding="UTF-8"?>
<root:report xmlns:flat="http://www.example.org/2" xmlns:root="http://www.example.org/1">
   <flat:Country>Sweden</flat:Country>
   <flat:SEK>42B</flat:SEK>
</root:report>

您需要使用 $json 变量。放在?的左边:

<flat:Country>{$json?general?Country}</flat:Country>
<flat:SEK>{$json?units-definitions?SEK}</flat:SEK>
        

只是为了说明您最初的尝试在哪种情况下会起作用:如果您将 parse-json 直接推送到 apply-templates 并在 XDM 地图上进行匹配,则该代码段会在该模板的上下文中起作用:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:root="http://www.example.org/1"
  xmlns:flat="http://www.example.org/2"
  exclude-result-prefixes="xs"
  expand-text="yes">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="data">
    <root:report>
      <xsl:apply-templates select="parse-json(.)"/>
    </root:report>
  </xsl:template>

  <xsl:template match=".[. instance of map(xs:string, item())]">
    <flat:Country>{?general?Country}</flat:Country>
    <flat:SEK>{?units-definitions?SEK}</flat:SEK>
  </xsl:template>

</xsl:transform>