我使用自动生成的代码工具来生成 xslt 代码,但我发现了一个问题。有时,声明的变量名是相同的,这会导致我的实现出现问题。让我举个例子。生成的代码是这样的:
<xsl:template name="My_Template">
<xsl:variable name="var7_map_of_House" as="xs:string*">
<xsl:for-each select="$var9_House/Item">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="var8_count_as_string" as="xs:string" select="xs:string(fn:count($var7_map_of_House))"/>
<xsl:variable name="var5_map_of_HCon" as="xs:string*">
<xsl:for-each select="$var9_House/Item/postcode">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="var7_map_of_House" as="xs:string" select="xs:string(fn:count($var5_map_of_HCon))"/>
<xsl:variable name="var1_map_of_HouseCon" as="xs:string*">
<xsl:for-each select="$var9_House/Item/name">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
</xsl:template>
如您所见,变量名“var7_map_of_House”被创建了两次,这导致了问题。我想创建另一个 xlst 或者可能是一个 python 脚本,但我相信 xslt 更好地识别声明两次的值并将这些值替换为唯一的值。例如,我有这个变量名称
variable name="var7_map_of_House"
如果我搜索 XSLT 并发现该值被使用两次或多次,我必须用唯一的名称替换该值,例如 "var27_map_of_House"
。此外,无论在其声明下使用此重复值,我都必须将其替换为新值。您知道这是否可以实现以及如何实现吗?我对 xslt 还很陌生。上面进行此转换的代码必须是:
<xsl:template name="My_Template">
<xsl:variable name="var7_map_of_House" as="xs:string*">
<xsl:for-each select="$var9_House/Item">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="var8_count_as_string" as="xs:string" select="xs:string(fn:count($var7_map_of_House))"/>
<xsl:variable name="var5_map_of_HCon" as="xs:string*">
<xsl:for-each select="$var9_House/Item/postcode">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="var27_map_of_House" as="xs:string" select="xs:string(fn:count($var5_map_of_HCon))"/>
<xsl:variable name="var1_map_of_HouseCon" as="xs:string*">
<xsl:for-each select="$var9_House/Item/name">
<xsl:sequence select="fn:string(.)"/>
</xsl:for-each>
</xsl:variable>
</xsl:template>
在非常粗略的层面上,如果您希望您的相关
xsl:variable
是例如的孩子xsl:template
,识别重复项并更改它们(下面我不会尝试将第二个var7_map_of_House
重命名为您所显示的内容,但对于var7_map_of_House2
,您可以使用键,例如
<xsl:key name="varname" match="xsl:variable" use="@name"/>
<xsl:template match="xsl:template/xsl:variable[not(. is key('varname', @name, ..)[1])]">
<xsl:copy>
<xsl:attribute name="name" select="concat(@name, index-of(key('varname', @name, ..)/generate-id(), generate-id()))"/>
<xsl:apply-templates select="@* except @name, node()"/>
</xsl:copy>
</xsl:template>
但是识别和转换以下同级元素以进行变量引用名称更改非常简单,我无法直接拼写出来,使用 XSLT 的当前版本 (3) 我想知道
xsl:iterate
是否可以帮助解决这个问题,并且/或者会考虑使用 for-each-group group-starting-with
来识别需要替换变量的节点“组”。