<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:attribute name="position"><xsl:call-template name="xpath.position"></xsl:call-template</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="xpath.position">
<xsl:param name="node" select="."></xsl:param> <!-- default value is current node -->
<xsl:param name="path" select="''"></xsl:param> <!-- default value is empty string -->
<!-- prepend the current position to $path, save it as next.path -->
<xsl:variable name="next.path"><xsl:text>*[position()=</xsl:text><xsl:value-of select="$node/count(preceding-sibling::*)+1"/><xsl:text>]</xsl:text>
<xsl:if test="$path != ''">/</xsl:if>
<xsl:value-of select="$path"></xsl:value-of>
</xsl:variable>
<xsl:choose>
<xsl:when test="$node/parent::*"> <!-- when there is a parent node -->
<xsl:call-template name="xpath.position">
<xsl:with-param name="node" select="$node/parent::*"></xsl:with-param>
<xsl:with-param name="path" select="$next.path"></xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:text>/</xsl:text>
<xsl:value-of select="$next.path"></xsl:value-of>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Tuesday, May 12, 2009
How to Get XPath to an XML Node
There are several XSL templates floating around that get a human readable path to a node. However, I found none that cover the case when there are multiple nodes of the same element at the same level. I came up with a complicated solution that kept the output human readable, but the solution for something machine readable is actually simple.
Subscribe to:
Post Comments (Atom)
Labels
- Java (34)
- Oracle (27)
- javascript (24)
- NIX administration (19)
- Reporting (18)
- XML (17)
- Web Graphics (10)
- perl (10)
- CSS (9)
- Tomcat (8)
- Android (7)
- Matlab (7)
- XSL (7)
- HTML (6)
- SQL (6)
- XForms (6)
- browser quirks (6)
- Orbeon XForms (5)
- Solaris (5)
- AJAX (4)
- Mirth Project (4)
- PHP (4)
- Video (4)
- Arduino (3)
- Eclipse (3)
- JPA (3)
- JSP (3)
- JSTL (3)
- LAMPS (3)
- SSH (3)
- SVN (3)
- Hibernate (2)
- Netbeans (2)
- Networking (2)
- Python (2)
- Windows (2)
- Wordpress (2)
- XHTML (2)
- Alfresco (1)
- Architecture (1)
- ArduPilot (1)
- Arduino Yun (1)
- Arduplane (1)
- Audio Recording (1)
- Betaflight (1)
- CouchDB (1)
- DIY (1)
- Design (1)
- FPV (1)
- JSON (1)
- JUnit (1)
- Mobile Development (1)
- Printing (1)
- RC Airplane (1)
- REST (1)
- Scalability (1)
- Struts (1)
- Tools (1)
- Virtualization (1)
- Web services (1)
- camera (1)
- canon (1)
- gphoto2 (1)
- jQuery (1)
- ubuntu (1)
- unix (1)
No comments:
Post a Comment