XSLT » Functions » generate-id

string = generate-id(node-set)
The optional node-set argument defines the target node-set. If the node-set contains more than one node, then only the first node in the set will be considered. If the node-set is empty, the empty string will be returned. If this argument is omitted, then as a default, an id will be generated for the context node.

The generate-id function is used to generate a string value that identifies a node. The string will begin with an alphabetic character followed by several additional alphanumeric characters. Within the application of a stylesheet, each returned string value will be unique.

Unfortunately, the generated id has no relationship to any id attribute in the source document. (Therefore, you cannot use the id or key functions to find or set this value.)
The primary purpose of this function is to provide a mechanism to create links in the output document that use the id. For example, if this function returned the string h144d7 for a specified node, then the link to that node would be: <a href="#h144d7">


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">

<xsl:for-each select="devguru_staff/programmer">
NAME: <a href="#{generate-id(name)}"><xsl:value-of select="name" /></a>
<hr />

<xsl:for-each select="devguru_staff/programmer">
NAME: <a name="{generate-id(name)}"><xsl:value-of select="name" /></a>
<p />
DOB: <xsl:value-of select="dob" />
<p />
AGE: <xsl:value-of select="age" />
<p />
ADDRESS: <xsl:value-of select="address" />
<p />
PHONE: <xsl:value-of select="phone" />
<hr />

NAME: Bugs Bunny
NAME: Daisy Duck
NAME: Minnie Mouse
NAME: Bugs Bunny

DOB: 03/21/1970
AGE: 31

ADDRESS: 4895 Wabbit Hole Road

PHONE: 865-111-1111
NAME: Daisy Duck

DOB: 08/09/1949
AGE: 51

ADDRESS: 748 Golden Pond

PHONE: 865-222-2222
NAME: Minnie Mouse

DOB: 04/13/1977
AGE: 24

ADDRESS: 4064 Cheese Factory Blvd

PHONE: 865-333-3333

Here we use generate-id twice in this example. We first create an index of links based upon the name, and then we create the name anchors. This is the code for xslt_example_generateid.xsl.
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_generateid.xsl"?>

Language(s): XSLT

See Also: