XML:
<Grandparent>
<Parent>
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children>
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children
</Parent>
</Grandparent>
XSLT:
<xsl:template match"/">
<xsl:apply-templates select="GrandParent/Parent/Children" />
</xsl:template>
<xsl:template match="Children">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="Children/Info/Name/label">
<xsl:copy>
<xsl:variable name="childCtr" select="Parent/Children[position()]"/>
<xsl:attribute name="text">
<xsl:value-of select="$childCtr"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!--Identity template copies content forward -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
如何在向label标签添加属性并获取整个“children”节点的同时使用模板获取“children”的索引或位置?
像:
Parent[0] = Children1,
Parent[1] = Children2,
Parent[2] = Children3
我怎么能得到这种东西?我需要一些帮助。提前致谢
答案 0 :(得分:2)
如果没有您的预期输出列表,很难说出您想要的内容,但也许就是这样......
此XSLT 1.0样式表......
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="label">
<label text="{count(../../../preceding-sibling::Children) + 1}">
<xsl:apply-templates select="@*|node()"/>
</label>
</xsl:template>
</xsl:stylesheet>
...应用于此输入时...
<Grandparent>
<Parent>
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children>
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children>
<Children>
<Info>
<Name>
<label id="chname"/>
</Name>
</Info>
</Children>
</Parent>
</Grandparent>
...会产生......
<Grandparent>
<Parent>
<Children>
<Info>
<Name>
<label text="1" id="chname" />
</Name>
</Info>
</Children>
<Children>
<Info>
<Name>
<label text="2" id="chname" />
</Name>
</Info>
</Children>
<Children>
<Info>
<Name>
<label text="3" id="chname" />
</Name>
</Info>
</Children>
</Parent>
</Grandparent>
答案 1 :(得分:1)
隧道(XSLT 2.0功能)由子模板设置的参数:
<xsl:template match="Children">
<xsl:copy>
<xsl:apply-templates select="@*|node()">
<xsl:with-param name="childPosition" select="position()" tunnel="yes"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="Children/Info/Name/label">
<xsl:param name="childPosition" tunnel="yes"/>
<xsl:copy>
<xsl:attribute name="text">
<xsl:value-of select="$childPosition"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
答案 2 :(得分:0)
试试这个:
<xsl:variable name="childCtr" select="count(ancestor::Children/preceding-sibling::Children)"/>