Skip to Main Content
XSLT
book

XSLT

by Doug Tidwell
August 2001
Intermediate to advanced content levelIntermediate to advanced
480 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from XSLT

How Do I List All the Elements in an XML Document?

As in our last example, this job is for generic XPath expressions. We’ll use the grouping techniques described in Section 6.2 in Chapter 6, along with the name() function, to accomplish this. Our stylesheet sorts all element names alphabetically, and then groups them to list each unique element once, along with a count of how many times that element appears:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:variable name="newline">
<xsl:text>
</xsl:text>
  </xsl:variable>

  <xsl:key name="elements" match="*" use="name()"/>

  <xsl:template match="/">
    <xsl:value-of select="$newline"/>
    <xsl:text>Summary of Elements</xsl:text>
    <xsl:value-of select="$newline"/>
    <xsl:value-of select="$newline"/>
    <xsl:for-each 
      select="//*[generate-id(.)=generate-id(key('elements',name())[1])]">
      <xsl:sort select="name()"/>
      <xsl:for-each select="key('elements', name())">
        <xsl:if test="position()=1">
          <xsl:text>Element </xsl:text>
          <xsl:value-of select="name()"/>
          <xsl:text> occurs </xsl:text>
          <xsl:value-of select="count(//*[name()=name(current())])"/>
          <xsl:text> times.</xsl:text>
          <xsl:value-of select="$newline"/>
        </xsl:if>
      </xsl:for-each>
    </xsl:for-each>
    <xsl:value-of select="$newline"/>
    <xsl:text>There are </xsl:text>
    <xsl:value-of select="count(//*)"/>
    <xsl:text> elements in all.</xsl:text>
  </xsl:template>
    
</xsl:stylesheet>

When we run this stylesheet against the XML source file ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning XSLT

Learning XSLT

Michael Fitzgerald
Inside XSLT

Inside XSLT

Steven Holzner
XSLT Cookbook

XSLT Cookbook

Sal Mangano
XSLT and XPATH: A Guide to XML Transformations

XSLT and XPATH: A Guide to XML Transformations

John Robert Gardner, Zarella L. Rendon

Publisher Resources

ISBN: 0596000537Supplemental ContentCatalog PageErrata