How to pass parameters to XSLT?

女生的网名这么多〃 提交于 2019-12-23 10:19:42

问题


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 tell 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?


回答1:


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.



来源:https://stackoverflow.com/questions/3251149/how-to-pass-parameters-to-xslt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!