Re: [xsl] is XPath 3.1 xml-to-json() function useful

Subject: Re: [xsl] is XPath 3.1 xml-to-json() function useful
From: "Martin Honnen martin.honnen@xxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Mon, 11 Mar 2019 06:34:33 -0000
Am 11.03.2019 um 07:04 schrieb Mukul Gandhi gandhi.mukul@xxxxxxxxx:
> I'm continuing on this topic.
>
> On Fri, Mar 8, 2019 at 4:39 PM Michael Kay mike@xxxxxxxxxxxx 
> <mailto:mike@xxxxxxxxxxxx> <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx 
> <mailto:xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>> wrote:
>
>     we decided on a different approach: provide a function to convert
>     a very specific XML vocabulary to JSON, and then (because we
>     already have powerful XML-to-XML transformation capabilities), let
>     the user say how their particular XML should be transformed to
>     that vocabulary.
>
>
> Lets say, we've a following input XML document,
>
> <?xml version="1.0" encoding="UTF-8"?>
> <root>
> B  B <val>1</val>
> B  B <val>2</val>
> B  B <val>3</val>
> B  B <val>4</val>
> </root>
>
> I would want to transform above XML document to following JSON,
>
> {
> B  B  "root": {
> B  B  B  B  "val": [
> B  B  B  B  B  B  1,
> B  B  B  B  B  B  2,
> B  B  B  B  B  B  3,
> B  B  B  B  B  B  4
> B  B  B  B  ]
> B  B  }
> }
>
> How can I do this with XSLT 3.0 and XPath 3.1's fn:xml-to-json() 
> function ?
>

You need to transform your XML to the format the function expects, if 
the input format is known, i.e. you know you have various "val" elements 
with numbers you want to be transformed to array items then it is rather 
easy:


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
 B B B  xmlns:xs="http://www.w3.org/2001/XMLSchema";
 B B B  exclude-result-prefixes="#all"
 B B B  xmlns="http://www.w3.org/2005/xpath-functions";
 B B B  expand-text="yes"
 B B B  version="3.0">

 B  <xsl:mode on-no-match="shallow-skip"/>

 B  <xsl:output method="text"/>
 B  <xsl:strip-space elements="*"/>

 B  <xsl:template match="root">
 B B B B B  <map>
 B B B B B B B B B  <map key="{local-name()}">
 B B B B B B B B B B B B B  <array key="val">
 B B B B B B B B B B B B B B B B B  <xsl:apply-templates/>
 B B B B B B B B B B B B B  </array>
 B B B B B B B B B  </map>
 B B B B B  </map>
 B  </xsl:template>

 B  <xsl:template match="val">
 B B B B B  <number>{.}</number>
 B  </xsl:template>

 B  <xsl:template match="/">
 B B B B  <xsl:variable name="json-xml">
 B B B B B B B B  <xsl:apply-templates/>
 B B B B  </xsl:variable>
 B B B B  <xsl:value-of select="xml-to-json($json-xml, map { 'indent' : 
true() })"/>
 B  </xsl:template>

</xsl:stylesheet>


https://xsltfiddle.liberty-development.net/ncdD7mc

Current Thread