当前位置: 动力学知识库 > 问答 > 编程问答 >

xml - Inherit attribute value through multiple recursive templates in XSL

问题描述:

Let's say I have an XML file that looks like this:

<a id="x">

<b>

<b>

<a id="y">

<b>

<c />

</b>

</a>

</b>

<c>

<a id="z">

<b>

<c />

</b>

</a>

</c>

</b>

</a>

After many hours of working, I've finally gotten it so that the "a", "b", and "c" templates recurse properly. The one probably I have left is that I need the value of a/@id to be available in b and c. But I also need to be able to reset that value when it gets to the inner a. (That is, in a#x > b > b > a#y > b > c I need the value 'y', but in a#x > b > b I need the value 'x'. In other words, I need the most ancestorally-recent value of a/@id.)

The problem is complicated by the fact that the b elements can be nested an indeterminate number of times, so it's not simply the case of doing ../../@id or something.

Since it doesn't seem like variables or parameters would work for this, I was thinking an acceptable workaround would be to automatically carry the @id down to each child element. However, I couldn't figure out a way to do this using xsl:attribute, as that always seems to modify the output tree, rather than the input or currently-processing tree.

Any tips?

网友答案:

Can't you just do ancestor::a[first()]/@id?

<xsl:template match="a">
   ...
   <xsl:apply-templates match="*" />
</xsl:template>

<xsl:template match="b">
   <xsl:variable name="id" select="ancestor::a[first()]/@id" />
   ...
   <xsl:apply-templates match="*" />
</xsl:template>

<xsl:template match="b">
   <xsl:variable name="id" select="ancestor::a[first()]/@id" />
   ...
   <xsl:apply-templates match="*" />
</xsl:template>
分享给朋友:
您可能感兴趣的文章:
随机阅读: