XSLT在不同的元素中设置来自另一个XML文件的属性值
这有点难以解释,所以我说的是XML 我要转换的XML文件XSLT在不同的元素中设置来自另一个XML文件的属性值,xml,xslt,Xml,Xslt,这有点难以解释,所以我说的是XML 我要转换的XML文件 <Items> <Item ID="1" Name="Student"> <Cell Name=""/> <Cell Number=""/> </Item> <Item ID="1" Name="Professor"> <Cell Name=""/> <Cell Number=""/> </Item> val
<Items>
<Item ID="1" Name="Student">
<Cell Name=""/>
<Cell Number=""/>
</Item>
<Item ID="1" Name="Professor">
<Cell Name=""/>
<Cell Number=""/>
</Item>
values.xml和所有属性值
<students>
<count>2</count>
<student number="1">
<name>Peter</name>
<number>1234</number>
</student>
<student number="2">
<name>Stefan</name>
<number>4567</number>
</student>
</students>
2.
彼得
1234
斯特凡
4567
所需输出
<Items>
<Item ID="1" Name="Student">
<Cell Name="Max"/>
<Cell Number="1234"/>
</Student>
<Item ID="2" Name=Student>
<Cell Name="Stefan"/>
<Cell Number="4567"/>
</Professor>
</Items>
我的想法
<xsl:variable name="total" select="document('values.xml')"/>
<!-- Identity Transformation --> ||WORKS FINE||
<!-- copy students n-times --> ||WORKS FINE||
<!-- set attribute: name --> ||DOESN'T WORK||
<xsl:template match="v:Items/Item/Cell[1]">
<xsl:param name="c" select="1"/>
<xsl:param name="values" select="$total/students/student[@number=$c]"/>
<xsl:copy>
<xsl:attribute name="Name">
<xsl:copy-of select="$values/name"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
<xsl:if test="$c < $total/students/count">
<xsl:apply-templates select=".">
<xsl:with-param name="c" select="$c+1"/>
</xsl:apply-templates>
</xsl:if>
</xsl:template>
||很好||
||很好||
||不行
我在每个元素中获得两个属性值。
但是我希望第一个属性值在第一个(Cell-)元素中,第二个属性值在第二个(Cell-)元素中,依此类推。编辑:实现这一点的一个较短的方法是计算XML中的位置,并使用它来获得
单元格和学生的索引
<xsl:template match="Items/Item">
<xsl:variable name="idx"><xsl:number /></xsl:variable> <!-- index of this 'Item' -->
<xsl:variable name="values" select="$total/student[@number=$idx]"/>
<xsl:copy>
<xsl:copy-of select="@*" /> <!-- copy attributes of this 'Item' -->
<xsl:apply-templates select="Cell">
<xsl:with-param name="cell" select="$values" /> <!-- pass current 'student' as parameter -->
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="Cell">
<xsl:param name="cell" />
<xsl:variable name="idx" select="position()" />
<xsl:variable name="firstAttr" select="name(@*[1])" /> <!-- get the name of the first attribute of this 'Cell' -->
<xsl:copy>
<xsl:attribute name="{$firstAttr}"> <!-- recreate attribute -->
<xsl:value-of select="$cell/*[$idx]"/> <!-- use position() of this 'Cell' as index in the current 'student' -->
</xsl:attribute>
</xsl:copy>
</xsl:template>
然后使用谓词限制上面的第一个模板:
<xsl:template match="Items/Item[@Name='Student']">
<xsl:variable name="idx" select="@ID"></xsl:variable>
...
...
<xsl:template match="Items/Item[@Name='Student']">
<xsl:variable name="idx" select="@ID"></xsl:variable>
...