xsl-list
[Top] [All Lists]

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

2019-03-08 16:38:50
On 08.03.2019 23:17, Martin Honnen martin(_dot_)honnen(_at_)gmx(_dot_)de wrote:
On 08.03.2019 23:07, Willem Van Lishout willemvanlishout(_at_)gmail(_dot_)com 
wrote:
I've been experimenting with the xml-to-json function, but for some reason my output is escaped. Why is that?

Stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
     xmlns:xs="http://www.w3.org/2001/XMLSchema"; xmlns:f="http://www.w3.org/2005/xpath-functions"; version="3.0">
     <xsl:output encoding="UTF-8" method="json"/>
     <xsl:template match="/">
         <xsl:variable name="transformed">
             <xsl:apply-templates select="programs"/>
         </xsl:variable>
         <xsl:value-of select="xml-to-json($transformed, map{'indent': true()})"/>

The function returns a string you can output as such with the xsl:output method="text", you have used "json" instead which then applies JSON escaping rules on the string you have.

You can use the "json" output method if your result is an XPath 3.1 value like an array or a map that can be serialized as JSON:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
    xmlns:mf="http://example.com/mf";
    exclude-result-prefixes="#all"
        version="3.0">

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

  <xsl:output method="json" indent="yes"/>

  <xsl:function name="mf:apply-templates" as="item()*">
      <xsl:param name="input" as="item()*"/>
      <xsl:apply-templates select="$input"/>
  </xsl:function>

  <xsl:template match="programs">
      <xsl:sequence select="array { mf:apply-templates(*) }"/>
  </xsl:template>

  <xsl:template match="program">
      <xsl:sequence select="map { 'title' : string(@title) }"/>
  </xsl:template>

</xsl:stylesheet>

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

Unfortunately XSLT 3 lacks an xsl:array instruction so I had to introduce that function on the XPath level to construct the array items.

If you use Saxon PE or EE you can use saxon:array instead.
--~----------------------------------------------------------------
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
EasyUnsubscribe: http://lists.mulberrytech.com/unsub/xsl-list/1167547
or by email: xsl-list-unsub(_at_)lists(_dot_)mulberrytech(_dot_)com
--~--

<Prev in Thread] Current Thread [Next in Thread>