如何解决使用函数“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>
解决方法
您需要使用 $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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。