我试图理解工作项目的一段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属性来应用它。
发布于 2018-03-23 10:11:19
如果我们认为apply-template类似于for-each,那么这种方法(即跨多个模板传递内容)很有用。在这个比较中,with-param类似于变量。
如果您需要通过多个模板传递一个变量,您可以在您看到的方法中完成此操作。因为当您输入MandatoryOrOptional时,在XMLString中分配给参数"name“的值超出了范围,所以当您输入MandatoryOrOptional模板时,您需要一种方法来指示什么是"name”。这样做的方法是将"name“作为参数传递。有效地将变量的范围扩展到新的模板中。
我已经在您的代码片段中添加了注释,以尝试“在代码中”详细说明这一点。
<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=“名称”是否是一个好的做法是有争议的,但我认为它是有意义的,并且已经使用了几次。这使得在代码中跟随“变量”变得更容易。
https://stackoverflow.com/questions/49364980
复制相似问题