实际上是XSLT Lookup(在循环期间存储变量并在其中使用另一个模板)

Kri*_*rgh 0 xslt

这个问题实际上有些不同.请参阅@ Tomalak的回答以了解OP真正想要的内容.:(

有没有办法在一个数组中的for-each循环期间存储变量/ param,并在另一个模板中使用它,即<xsl:template match="Foundation.Core.Classifier.feature">.classname应存储for-each期间出现的所有值.你会如何在XSLT中实现它?这是我目前的代码.

<xsl:for-each select="Foundation.Core.Class">       
 <xsl:for-each select="Foundation.Core.ModelElement.name">
  <xsl:param name="classname">
   <xsl:value-of select="Foundation.Core.ModelElement.name"/>
  </xsl:param>
 </xsl:for-each>
 <xsl:apply-templates select="Foundation.Core.Classifier.feature" /> 
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

这是classname应该使用参数的模板.

<xsl:template match="Foundation.Core.Classifier.feature">
 <xsl:for-each select="Foundation.Core.Attribute">
  <owl:DatatypeProperty rdf:ID="{Foundation.Core.ModelElement.name}">
   <rdfs:domain rdf:resource="$classname" />
  </owl:DatatypeProperty>
 </xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

输入文件可以在http://krisvandenbergh.be/uml_pricing.xml找到

Tom*_*lak 5

不,不可能在for-each循环中存储变量并在以后使用它.

这是因为变量在XSLT中是一次写入的(一旦设置它们是不可变的),并且它们在其父元素中严格限定范围.一旦处理离开for-each循环,变量就消失了.

XSLT不能作为命令式编程语言,但这就是你在这里尝试的东西.你并不需要<xsl:for-each>在所有的情况下,98%,因为它堵塞你的XSLT是如何工作的看法不应该使用它.要改进你的XSLT代码,摆脱<xsl:for-each>你拥有的所有循环(所有这些,我的意思是)并使用模板代替:

<xsl:template match="Foundation.Core.Class">
  <xsl:apply-templates select="
    Foundation.Core.Classifier.feature/Foundation.Core.Attribute
  " />
</xsl:template>

<xsl:template match="Foundation.Core.Attribute">
  <owl:DatatypeProperty rdf:ID="{Foundation.Core.ModelElement.name}">
    <rdfs:domain rdf:resource="{
      ancestor::Foundation.Core.Class[1]/Foundation.Core.ModelElement.name[1]
    }" />
  </owl:DatatypeProperty>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

(我不确定上面是否是你真正想要的,你的问题很模糊.)

注意使用XPath ancestor轴来引用层次结构中较高的元素(您似乎需要<Foundation.Core.ModelElement.name>父类的元素).

PS:由于结构化元素名称,您的XML非常臃肿且冗余.结构应该来自......井...... 结构,而不是来自像<Foundation.Core.Classifier.feature>.不过,我不确定你是否可以采取任何措施.


加成:

为您解决xmi.id/ xmi.idref问题,最好的办法是使用XSL键:

<!-- this indexes all elements by their @xmi.id attribute -->
<xsl:key name="kElementByIdref" match="*[@xmi.id]" use="@xmi.id" />

<!-- now you can do this -->
<xsl:template match="Foundation.Core.DataType">
  <dataTypeName>
   <!-- pull out the corresponding element from the key, output its value -->
   <xsl:value-of select="key('kElementByIdref', @xmi.idref)" />
  </dataTypeName>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

为了更好地理解密钥如何在内部工作,您可以阅读我之前给出的答案.不要过多地回答这个问题,只要阅读我的答案的下半部分,我就用JavaScript解释了密钥.