Search code examples
jsonapisaxonxslt-3.0

Fetch JSON from API using XSLT


I need to fetch a JSON file from an API using XSLT 3, something like this would be in python:

    import urllib.request, json 
    with urllib.request.urlopen("http://dme-intern.mozarteum.local/digital-editions/api/work-info/4087") as url:
        data = json.load(url)
        print(data)

First I tried it with doc('http://dme-intern.mozarteum.local/digital-editions/api/work-info/4087') but as the function expects an XML document I'm getting this error:

Content is not allowed in prolog.

Otherwise it seems that this extension dp:url-open would yield the needed result (cf. this post). However, when invoking an XSLT transformation using Saxon EE 11.4 I'm getting this error:

Unknown extension instruction

I suppose that the extension should be somehow declared for Saxon (?) I've searched in the Saxon documentation like this section but did not find what I need.

Here is my test XSLT:

    <?xml version="1.0" encoding="UTF-8"?>
    <stylesheet exclude-result-prefixes="xs xd dme functx dp" version="3.0"
      xmlns:dp="http://www.datapower.com/extensions" extension-element-prefixes="dp"
      xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:dme="http://www.mozarteum.at/ns/dme"
      xmlns:functx="http://www.functx.com" xmlns:map="http://www.w3.org/2005/xpath-functions/map"
      xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" xmlns:xi="http://www.w3.org/2001/XInclude"
      xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xpath-default-namespace="http://www.music-encoding.org/ns/mei">
    
   <template match="/">
      <variable name="test">
        <dp:url-open target="http://dme-intern.mozarteum.local/digital-editions/api/work-info/4087"/>
      </variable>
    <copy-of select="$test"/>
  </template>
    
    </stylesheet>

P.S. I'm invoking the transformation using oXygen XML editor 25.0, build 2023013006.


Solution

  • If you get JSON from that API you can use json-doc('http://dme-intern.mozarteum.local/digital-editions/api/work-info/4087') to have an XPath 3.1/XSLT 3.0 XDM map or array in your XSLT code. To select/find data in XDM maps/arrays see https://www.altova.com/training/xpath3/xpath-31#new-xpath-3.1-operators or the similar sections in the XPath 3.1 spec on arrays and maps and using the lookup operator https://www.w3.org/TR/xpath-31/#id-lookup.

    If you want an XML representation of the JSON use unparsed-text('http://dme-intern.mozarteum.local/digital-editions/api/work-info/4087') => json-to-xml() instead.