简体   繁体   中英

How to pass parameter value to XSL?

Suppose I have a XSL as follows:

<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  version="1.0">
  <xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" indent="yes"/>
    <xsl:param name="sortKey" select="'firstname'"/>
</xsl:stylesheet>

Then a XML as follows

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="XYZ.xsl"?>
<ABC>
     <firstname>GREG</firstname>
</ABC>

I want to pass a value to the XSL parameter firstname from XML. Can I do that? If yes, How?

It looks from the answers that this is not possible.

What about reading the value from the same XML and assigning it to the parameter. Can this be done? If yes, how?

Because the value you want as a parameter is in your base XML, you can simply enter a XPath expression for the paramater that specifies a default value.

<xsl:param name="sortKey" select="/ABC/firstname"/> 

Simply using an variable, would also be valid here, if the value was always going to be in the XML

<xsl:variable name="sortKey" select="/ABC/firstname"/> 

And then, to use this parameter/variable, you would simply do something like this

<xsl:template match="/">
    <xsl:value-of select="$sortKey" />
</xsl:template>

This would simply output the value GREG

假设您正在使用.NET进行转换,则可以在这里找到该重复的问题的答案: 通过.NET将参数传递给XSLT样式表

The W3C has not proposed a mechanism. It's possible to define a new processing instruction which is capable of doing this. But if you're planning on using this in a browser or other existing tool, it's not a viable option to pass parameters into stylesheets which are invoked through processing instructions.

An alternative option is to place your "parameter" in an alternate document, and load it using something like the document() function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM