JSON to XML conversing USING XSLT 3.0

人盡茶涼 提交于 2020-04-17 21:54:17

问题


I have using Windows and SAXON 9.9(HE).

My JSON Code is:

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

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>

My required output XML is:

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

How do achieve this?


回答1:


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

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>

or with some combination of the two.

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.



来源:https://stackoverflow.com/questions/61096727/json-to-xml-conversing-using-xslt-3-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!