xslt中获得xml 节点后 能不能反过来再获取该节点的xpath路径、
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <table border="1"> <tr bgcolor="#9acd32"> <th align="left">Title</th> <th align="left">Artist</th> <th align="left">Price</th> </tr> <xsl:for-each select="catalog/cd"> <tr xpath="????"> <xsl:attribute name="xpath"> //我想给tr添加一个xpath 属性,而属性值就是当前节点的(cd)xpath路径该怎么做? </xsl:attribute> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="aritst"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
<xsl:template name="getxpath" > <xsl:variable name="position" select="position()"/> <xsl:variable name="nodename" select="name()" /> <xsl:if test="child::text() and not(@id)"> <xsl:attribute name="id" > <xsl:for-each select="ancestor-or-self::*"> <xsl:value-of select="name()"/> <xsl:if test="name()=$nodename"> <xsl:value-of select="concat('[',$position,']')" /> </xsl:if> <xsl:if test="not(position()=last())"> <xsl:value-of select="'/'"/> </xsl:if> <xsl:if test="position()=last()"> <xsl:value-of select="'/Text()'"/> </xsl:if> </xsl:for-each> </xsl:attribute> </xsl:if> </xsl:template>
<xsl:call-template name="getxpath" />
基本上可以解决这个问题,但是只有最后的元素才有position,中间的position还是不知道怎么处理,但是已经可以唯一的定位这个位置了,如果有更好的方法还望大神分享
<thead valign="bottom"> <tr> <td valign="top" id="COMMENTARYDOC/comm:body/level/level/bodytext/p/table/tgroup/thead/row/entry[1]/Text()">Guide card</td> <td valign="top" id="COMMENTARYDOC/comm:body/level/level/bodytext/p/table/tgroup/thead/row/entry[2]/Text()">Chapter</td> <td valign="top" id="COMMENTARYDOC/comm:body/level/level/bodytext/p/table/tgroup/thead/row/entry[3]/Text()">Paragraph numbers</td> </tr> </thead>