【问题标题】:Using apply-templates element to select and input values by parameters使用 apply-templates 元素通过参数选择和输入值
【发布时间】:2018-03-19 14:08:38
【问题描述】:

我正在尝试理解一个工作项目的一段 XSLT 代码,但我无法弄清楚什么调用了什么以及如何正确传递值。

我有这段代码,它使用 apply-templates 元素来选择文档类型元素中的第一个元素:

<xsl:apply-templates select="DocumentType[string(text())][1]" mode="XmlString">
        <xsl:with-param name="name" select="'DocumentType'"/>
      </xsl:apply-templates>

然后将一个参数传递到模板中,该模板分配正确的值。 with-param 中的 name 属性与此处的 param 元素匹配:

<xsl:template match="*" mode="XmlString">
    <xsl:param name="name"/>
    <!-- Check the "name" parameter : madantory / optional -->
    <xsl:call-template name="MandatoryOrOptional">
      <xsl:with-param name="name" select="$name"/>
      <xsl:with-param name="value" select="."/>
    </xsl:call-template>
  </xsl:template>

但我不确定为什么以及如何传递该值。每当需要映射一个值时,它会在整个映射中重复使用。

通常我只会创建所需的标签并使用 xsl:value-of 元素从源文档中获取我想要的值。如果有人能告诉我这段代码在实践中是如何工作的,我将不胜感激。有几次我使用 apply-templates,我已经在我的 XSLT 中定义了一个模板,然后使用 match 属性来应用它。

【问题讨论】:

  • 这不是设计师会做的事情。这是你真的需要复制的模式吗?也许最初的开发者试图变得太聪明以至于其他人无法效仿。 :(
  • 第一个语句是什么意思?是的,如果可能,我想复制这种模式,因为它被广泛使用。
  • 我的意思是这不是 BizTalk Mapper 会做的事情。

标签: xml xslt biztalk biztalk-mapper


【解决方案1】:

如果我们认为 apply-template 类似于 for-each,则此方法(即,跨多个模板传递某些内容)很有用。在这个比较中,with-param 类似于变量。

如果您需要通过多个模板传递变量,您可以在您看到的方法中执行此操作。因为在输入 MandatoryOrOptional 时分配给 XMLString 中的参数“name”的值超出了范围,所以当您输入 MandatoryOrOptional 模板时,您需要一种方法来指示“name”是什么。这样做的方法是将“名称”作为参数传递。有效地将变量的范围扩展到新模板中。

我已将 cmets 添加到您的代码 sn-p 以尝试详细说明此“代码”。

<xsl:template match="*" mode="XmlString">
    <xsl:param name="name"/> 
        <!--This brings the name from the first template and stores it -->
        <!--This is treated as a variable with a scope of the template -->
    <xsl:call-template name="MandatoryOrOptional">
      <xsl:with-param name="name" select="$name"/>
         <!-- This effectively expands the scope of the variable $name -->
         <!-- The name sent from the first template is now in scope for MandatoryOrOptional -->
      <xsl:with-param name="value" select="."/>
    </xsl:call-template>
</xsl:template>

为每个参数保留 name="name" 是否是一种好习惯尚有争议,但我认为这是有道理的,并且已经多次使用它。通过代码更容易跟踪“变量”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多