arrays in xslt - are they possible?

S

sqad

I want to be able to write a static array in my XSLT 2 stylesheet. Can
someone please give me an example on how to do it and how to do the
lookup?

Thanks,
sqad
 
T

TOUDIdel

Uzytkownik "sqad said:
I want to be able to write a static array in my XSLT 2 stylesheet. Can
someone please give me an example on how to do it and how to do the
lookup?

it isn't good thinking way. xslt isn't programing language - remember of it.
 
P

Pavel Lepin

TOUDIdel said:
it isn't good thinking way. xslt isn't programing language
- remember of it.

The hell it isn't. XSLT is a declarative, rule-based
programming language. It's a DSL, not a general-purpose
language, but nevertheless it's actually Turing-complete.
Google 'xslt turing machine'.

To answer the OP's question, while XSLT doesn't have an
array data type, you can implement a static lookup table
this way:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:lt="http://example.org/lookup-table">
<xsl:param name="key"/>
<lt:lookup-table>
<lt:pair key="foo" value="1"/>
<lt:pair key="bar" value="2"/>
<lt:pair key="baz" value="3"/>
</lt:lookup-table>
<xsl:template match="/">
<value>
<xsl:apply-templates
select=
"
document('')
/xsl:stylesheet/lt:lookup-table
/lt:pair[@key=$key]/@value
"/>
</value>
</xsl:template>
</xsl:stylesheet>

Let's see:

pavel@debian:~/dev/xslt$ xsltproc --stringparam key foo
lookup.xsl lookup.xsl
<?xml version="1.0"?>
<value xmlns:lt="http://example.org/lookup-table">1</value>
pavel@debian:~/dev/xslt$ xsltproc --stringparam key bar
lookup.xsl lookup.xsl
<?xml version="1.0"?>
<value xmlns:lt="http://example.org/lookup-table">2</value>
pavel@debian:~/dev/xslt$ xsltproc --stringparam key baz
lookup.xsl lookup.xsl
<?xml version="1.0"?>
<value xmlns:lt="http://example.org/lookup-table">3</value>
pavel@debian:~/dev/xslt$

Alternatively, using keys:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:lt="http://example.org/lookup-table">
<xsl:param name="key"/>
<xsl:key name="key" match="lt:pair" use="@key"/>
<lt:lookup-table>
<lt:pair key="foo" value="1"/>
<lt:pair key="bar" value="2"/>
<lt:pair key="baz" value="3"/>
</lt:lookup-table>
<xsl:template match="/">
<value>
<xsl:for-each select="document('')">
<xsl:apply-templates
select="key('key',$key)/@value"/>
</xsl:for-each>
</value>
</xsl:template>
</xsl:stylesheet>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top