Home > Blockchain >  Is there a way to generate a lookup table using XSL?
Is there a way to generate a lookup table using XSL?

Time:06-21

I am trying to generate a lookup table using XSL given an xml file.

I have a data set that changes periodically, I need to use this data as a lookup table in another XSL (2.0) script. I currently have the lookup table hard coded in my XSL script but since the data changes, its a pain the behind updating the script.

I want to generate this lookup table as an external file and refer to it from my other script.

the xml with the data that is used to generate the lookup table looks like this:

<doc>
    <BO>
        <RTS>
            <Code>001</Code>
            <Val>74</Val>
        </RTS>
        <RTS>
            <Code>002</Code>
            <Val>111</Val>
        </RTS>
   <!-- Lots more -->
   <BO>
<doc>

The current lookup table (that is imbedded) looks like this:

<xsl:variable name="lookup" >
        <row Code="001"   Val="74"/>
        <row Code="002"   Val="111"/>
        <!-- Lots more -->
</xsl:variable>

I am not sure if the external file lookup table needs to be in a different format(?). As long as I can generate the lookup table and be able to use it from my current script is fine.

Edit: just to clarify, (I'm new to XSL) I am looking for guidance of how to use the input xml as a lookup table in my XSL.

CodePudding user response:

I am looking for guidance of how to use the input xml as a lookup table in my XSL.

You did not post your XSL or your XML input. Consider the following example, based - loosely - on your previous question:

XML

<input>
    <object>
        <code>002</code>
    </object>
    <object>
        <code>001</code>
    </object>
</input>

lookup.xml

<doc>
    <BO>
        <RTS>
            <Code>001</Code>
            <Val>74</Val>
        </RTS>
        <RTS>
            <Code>002</Code>
            <Val>111</Val>
        </RTS>
        <!-- Lots more -->
    </BO>
</doc>

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="lookup-path">lookup.xml</xsl:param>

<xsl:key name="lookup" match="RTS" use="Code"/>
  
<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="object">
    <xsl:copy>
        <xsl:copy-of select="code"/>
        <xsl:copy-of select="key('lookup', code, document($lookup-path))/Val"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<input>
   <object>
      <code>002</code>
      <Val>111</Val>
   </object>
   <object>
      <code>001</code>
      <Val>74</Val>
   </object>
</input>
  • Related