首页 > 解决方案 > 使用函数“parse-json”进行转换会返回错误

问题描述

我正在尝试使用函数“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>

标签: xmlxsltxslt-3.0

解决方案


您需要使用该$json变量。把它放在左边?

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

推荐阅读