将参数传递给XSLT样式表

12
我正在尝试向XSLT样式表传递一些参数。我按照这个例子进行了操作:通过.NET传递参数到XSLT样式表。但是我的转换页面没有正确显示值。以下是我的C#代码。由于Visual Studio 2010不使用XSLT 2.0,我不得不添加自定义函数来执行一些算术运算。
  var args = new XsltArgumentList();
  args.AddExtensionObject("urn:XslFunctionExtensions", new XslFunctionExtensions());
  args.AddParam("processingId", string.Empty, processingId);

  var myXPathDoc = new XPathDocument(claimDataStream);
  var xslCompiledTransformation = new XslCompiledTransform(true);

  // XSLT File
  xslCompiledTransformation.Load(xmlReader);

  // HTML File
  using (var xmlTextWriter = new XmlTextWriter(outputFile, null))
  {
      xslCompiledTransformation.Transform(myXPathDoc, args, xmlTextWriter);
  }

这是我的XSLT:

    <xsl:template match="/">
    <xsl:param name="processingId"></xsl:param>
    ..HTML..
    <xsl:value-of select="$processingId"/>

我有什么遗漏吗?


你在顶层有 <xsl:param name="processingId"> 吗?看起来你在模板内定义了参数,这将创建一个局部参数。对于外部参数,参数必须是全局的,因此必须在与 xsl:template 元素相同的级别上定义。 - Pawel
我不确定您在顶层指的是什么。参数定义在<xsl:template match="/">下面,就像我在问题中粘贴的那样。在上面是xsl:stylesheet标签。 - coson
我的意思是它不应该在xsl:template内部。尝试像这样做: <xsl:stylesheet ...> <xsl:param name="processingId" /><xsl:template match="/"><xsl:value-of select="$processingId"/>... - Pawel
1个回答

16

这是我的XSLT:

<xsl:template match="/">     
  <xsl:param name="processingId"></xsl:param>     
  ..HTML..     
  <xsl:value-of select="$processingId"/> 

我是否遗漏了什么?

是的,您遗漏了一个事实,即XSLT转换程序的调用者可以设置全局级别参数的值--而不是模板级别参数的值。

因此,代码必须为:

 <xsl:param name="processingId"/>     

 <xsl:template match="/">     
   ..HTML..     
   <xsl:value-of select="$processingId"/> 
   <!-- Possibly other processing here  -->
 </xsl:template>

2
这实际上是一个非常方便的知识点,有人知道是否也可以使用Java来完成吗? - adam5990
1
@adam5990,是的,如果使用的特定XSLT处理器是用Java编写的。以编程方式指定全局参数值的方法是与实现相关的,并且因XSLT处理器而异。例如,请参阅Saxon文档的此部分:saxonica.com/documentation/#!using-xsl/embedding/…。特别是在第1点下面写道:“您可以使用XsltTransformer上的方法为全局样式表参数设置值”。请注意,手动执行此操作并从命令行调用XSLT转换要简单得多。 - Dimitre Novatchev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接