Need to find the parent node id
This is my sample input
<table id="1" style="width=100%">
<tr>
<td id="1">
<table开发者_如何学Go id="2" style="width=50%">
<tr>
<td id="2">
</td>
</tr>
</table>
</td>
</tr>
</table>
I am using xslt1.0. when ever the template match 'td' is matched, i need to find the corresponding table id value..For example, If the td with id=1 is matched,i want to take style attribute value from table(id=1) and if the td with id=2 is matched,i want to take style attribute value from table(id=2). I have written ancestor::table/@style
in my template, but both td are referring the styles of table with id=1.
I have written
ancestor::table/@style
in my template
You were close. Because there can be more than one table
in the ancestor
axis, you need to get the first one like in ancestor::table[1]/@style
. Of course, if you are absolute sure there is always a chain of table
-> tr
-> td
(not optional tbody
) then you could go with @Flack's answer.
Assuming you are in 'td' context, use this XPath:
../../@style
Test XSLT against your sample:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="td">
<xsl:value-of select="../../@style"/>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
Result:
width=100%width=50%
Try this XPath it works perfectly
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="td">
<xsl:value-of select="ancestor::table[1]/@style"/>
<xsl:apply-templates/>
</xsl:template>
Result:
width=100%width=50%
精彩评论