I have XML which looks like this:
<A></A>
<A></A>
<A>
<a/>
<a/>
</A>
As you can see it has two levels <A> and <a>.
I wrote XSL tranform that generates index number on every <A> element and it works:
<xsl:template match "A">
<xsl:element name="Person">
<xsl:attribute name="id">
<xsl:number count="A"/>
</xsl:attribute>
</xsl:element>
</xsl>
Output:
<Person id="1"/>
<Person id="2"/>
<Person id="3"/>
But how to write xsl:number to generate the same number at <a> level (at ???)?
<xsl:template match "A">
<xsl:element name="Person">
<xsl:attribute name="id">
<xsl:number count="A"/>
<xsl:apply-templates select="a"/>
</xsl:attribute>
</xsl:element>
</xsl>
<xsl:template match "a">
<xsl:element name="Item">
<xsl:attribute name="id">
<xsl:number count="???"/>
</xsl:attribute>
</xsl:element>
</xsl>
Expected output (I want the same id for <Person> and <Item>):
<Person id="1"/>
<Person id="2"/>
<Person id="3">
<Item id="3"/>
<Item id="3"/>
</Person>
I know this must be some simple XPATH expression, but I really got stucked on this.
In response to your request to do it without passing a variable, see below.
The drawback is that
<xsl:number>can’t be used directly in an Attribute Value Template (as @Martin used the$idvariable), so generating theidattribute becomes verbose.(Untested.)
The key here is using
select=".."onxsl:numberin the"a"template. Edit: It turns out that theselect=".."is not actually necessary. Since the context nodeadoes not match the count patternA, it starts from the nearest ancestor that does match it. What a web of useful defaults this instruction has!