首页 > 解决方案 > 如何使用 XSLT 将 JSON 转换为 XML?

问题描述

我想使用 XSLT 将 JSON 转换为 XML。但无法达到预期的输出。下面是 JSON 请求:

{
    "Store": [
        {
            "Book": "Cartoons",
            "ID": "ABC"
        }
    ]
}

我尝试过的 XSLT:

 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl"
    xmlns:emp="http://www.semanticalllc.com/ns/employees#"
    xmlns:h="http://www.w3.org/1999/xhtml"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:j="http://www.w3.org/2005/xpath-functions"
    exclude-result-prefixes="xs math xd h emp"
    version="3.0"
    expand-text="yes">

<xsl:template match="/">
    <xsl:copy>
        <xsl:apply-templates select="json-to-xml(.)/*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*[@key]" xpath-default-namespace="http://www.w3.org/2005/xpath-functions">
    <xsl:element name="{@key}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

但是我得到了空的响应。

标签: jsonxmlxsltibm-datapower

解决方案


模式 match="/" 匹配文档节点(XML 树的根)。如果输入是 JSON,它将与您的输入不匹配。

XSLT 3.0 实际上并不擅长使用模板规则处理 JSON:它可以做到,但不是很方便。使用函数通常更方便。您可以将 JSON 输入作为 xsl:param 的值提供,并在您的xsl:initial-template;代码中处理它。或者,如果您感觉更有野心,您实际上可以通过调用xsl:function将 JSON 输入作为参数的公共来启动 XSLT 处理。

样式表的传统match="/"条目仅适用于 XSLT 处理 XML 输入文档的传统用途。


推荐阅读