1

I am using xslt 3.0(saxon-HE v11.4 library) to convert json to xml in Java.

Need help to extract value from an array

Sample Input json

{
"Details":{
"name":["a","b","c"]
}
}

Require output in below format

<Details>
<name indexarray="0">a</name>
<name indexarray="1">b</name>
<name indexarray="2">c</name>
</Details>

1 Answer 1

2

Well, with Saxon 11 you can literally feed the JSON with e.g. -json:input.json to the XSLT, then match e.g. .[. instance of map(*)]

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">
  
<xsl:output indent="yes"/>

<xsl:template match=".[. instance of map(*)]">
  <Details>
    <xsl:iterate select="?Details?name?*">
      <name indexarray="{position() - 1}">{.}</name>
    </xsl:iterate>
  </Details>
</xsl:template>
  
</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

2 Comments

I would tend to use xsl:for-each rather than xsl:iterate, but only on some sort of principle of using the tool of least power for the job.
@MichaelKay, kind of didn't want to answer a question tagged as for-loop with a use of xsl:for-each :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.