I have a problem.
I have an XML file that contains information about 100 courses.
I have an XSL file that nicely displays the list of 100 courses.
But what if I want to only display 1 course. Can I pass a parameter to the XSLT file to tel开发者_如何学Cl it to only display "ENGL 100" ?
The XML looks something like this:
<document>
<menu>
<item>
<name>MTH 300</name>
<brief>Mathematics Skill Development</brief>
<description>A course in the fundamentals of ...</description>
</item>
<item>
<name>MTH 301</name>
<brief>Basic Algebra</brief>
<description>An introduction to algebra, ...</description>
</item>
...
I know I could write an XSLT file called "eng100.xsl" to loop through the XML and display only ENG 100 but I don't want to have to write dozens of these files.
The XML is dynamic and I am able to control it. I want the XSLT file to be static and never change.
Is there any way to pass parameters into the XSLT?
You can pass parameters to XSLT, how this is done depends on your XSLT processor, but usually as additional command arguments, if it's a command-line processor.
You declare parameters using
<xsl:param name="courseName" select"initialValue"/>
You can then test this parameter in your XSLT, and invoke a different template depending on it's value. For example, if the parameter is empty, then invoke the current template that processes all elements, otherwise invoke a template that only processes elements when the item name equals the parameter value. You can do this with a test
<xsl:template match="item">
<xsl:if test="$courseName=name(./name)">
<xsl:call-template name="yourOriginalTemplate"/>
</xsl:if>
</xsl:template>
But by filtering and formatting, you are mixing two concerns in one file. I would separate out the selection of the XML elements from formatting - have two xslt files for that and run them as a pipeline.
精彩评论