How to convert US State name into state code ISO 3166-2 in xslt 3.0

Viewed 41
1 Answers

You can do it like this, using https://gist.github.com/HarishChaudhari/9465648#file-us-states-json-array-json:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">
  
  <xsl:param name="json-uri" as="xs:string" expand-text="no">https://gist.githubusercontent.com/HarishChaudhari/9465648/raw/6df23a7d934df3bcb213a74876d2b610e913b6de/us-states-json-array.json</xsl:param>

  <xsl:variable name="state-mapping-array" select="json-doc($json-uri)"/>
  
  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="state">
    <xsl:copy>
      <xsl:attribute name="code" select="$state-mapping-array?*[?name = current()]?iso_code"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

Or perhaps, to wrap it into a function:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all"
    version="3.0">
  
  <xsl:param name="json-uri" as="xs:string" expand-text="no">https://gist.githubusercontent.com/HarishChaudhari/9465648/raw/6df23a7d934df3bcb213a74876d2b610e913b6de/us-states-json-array.json</xsl:param>

  <xsl:variable name="state-mapping-array" select="json-doc($json-uri)"/>
  
  <xsl:function name="mf:get-state-code" as="xs:string?" cache="yes">
    <xsl:param name="state-name" as="xs:string"/>
    <xsl:sequence select="$state-mapping-array?*[?name = $state-name]?iso_code"/>
  </xsl:function>
  
  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="state">
    <xsl:copy>
      <xsl:attribute name="code" select="mf:get-state-code(.)"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>
Related