本文介绍了使用 XSLT 3.0 进行 JSON 到 XML 的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 WindowsSAXON 9.9(HE).

我的 JSON 代码是:

My JSON Code is:

{"analystId": "Test","jobId": "","profileData":{"allAuthorCoverage": false,"abc":"xyz","assetClasses":[{"status":测试1"}]}}

我的 XSLT 代码是:

MY XSLT Code is:

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:param name="input" select="'simple3.json'"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="init">
<xsl:apply-templates select="json-to-xml(unparsed-text($input))" mode="copy"/>
</xsl:template>
<xsl:template match="node() | @*" mode="copy">
<xsl:copy>
<xsl:apply-templates select="node() | @*" mode="copy"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

我需要的输出 XML 是:

My required output XML is:

<root>
<analystId>Test</analystId>
<jobId></jobId>
<profileData>
<allAuthorCoverage>false</allAuthorCoverage>
<abc>xyz</abc>
</profileData>
</root>

如何实现这一目标?

推荐答案

在 XSLT 3.0 中有几种方法可以处理这种转换.

There are several ways to approach this conversion in XSLT 3.0.

一种方法是使用 json-to-xml(),然后转换生成的 XML.生成的 XML 是

One way is to use json-to-xml(), and then transform the resulting XML. The resulting XML is

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="analystId">Test</string>
   <string key="jobId"/>
   <map key="profileData">
      <boolean key="allAuthorCoverage">false</boolean>
      <string key="abc">xyz</string>
      <array key="assetClasses">
         <map>
            <string key="status">Test1</string>
         </map>
      </array>
   </map>
</map>

并且您可以使用通用规则对其进行转换,例如

and you can transform it either with generic rules such as

<xsl:template match="*[@key]">
  <xsl:element name="{@key}">
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>

或具有特定规则,例如:

or with specific rules like:

<xsl:template match="fn:string[@key='analystId']>
  <analystId>{.}</analystId>
</xsl:template>

或两者的某种组合.

第二种方法是为所需的输出 XML 编写模板,然后深入解析 JSON 以在需要时提取特定值:

The second way to do it is to write a template for the desired output XML and then dive into the parsed JSON to extract specific values where required:

<xsl:template name="xsl:initial-template">
  <xsl:variable name="json" select="parse-json(....)"/>
  <root>
    <analystId>{$json?analystId}</analystId>
    <jobId>{$json?jobId}</jobId>
    <profileData>
      <allAuthorCoverage>{$json?profileData?allAuthorCoverage}</allAuthorCoverage>
      <abc>{$json?profileData?abc}</abc>
    </profileData>
  </root>
</xsl:template>

对于这个简单的例子,第二种方法可能是最简单的,但我怀疑第一种方法可以更好地扩展到更复杂的实际用例.

For this simple example, the second approach is probably easiest, but I suspect the first approach scales better to more complex real-world use cases.

这篇关于使用 XSLT 3.0 进行 JSON 到 XML 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:02
查看更多