XML Tutorials - Herong's Tutorial Examples - Version 5.05, by Dr. Herong Yang
Examples of Using "for-each" Elements
This section provides a tutorial example on how to use 'for-each' elements to loop through a set of elements, attributes, text contents and comments.
Now we are ready to do more complex tests to see the power of XSLT loop statements. Let's revise our dictionary.xsl:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- dictionary.xsl, version 2.0 - Copyright (c) 2014, HerongYang.com, All Rights Reserved. --> <xsl:template match="dictionary"> <pre> d_dictionary <xsl:for-each select="word"> w__<xsl:value-of select="name()"/> <xsl:apply-templates select="."/> </xsl:for-each> </pre> </xsl:template> <xsl:template match="word"> <xsl:for-each select="@*"> a___<xsl:value-of select="name(.)"/>=<xsl:value-of select="."/> </xsl:for-each> <xsl:for-each select="*"> e___<xsl:value-of select="name()"/> <xsl:apply-templates select="."/> </xsl:for-each> </xsl:template> <xsl:template match="name"> <xsl:for-each select="text()"> t____<xsl:value-of select="."/> </xsl:for-each> </xsl:template> <xsl:template match="definition"> <xsl:for-each select="text()"> t____<xsl:value-of select="."/> </xsl:for-each> </xsl:template> <xsl:template match="update"> <xsl:for-each select="@*"> a____<xsl:value-of select="name(.)"/>=<xsl:value-of select="."/> </xsl:for-each> </xsl:template>
Opening dictionary_xsl.xml with Internet Explorer, I got:
d_dictionary w__word a___acronym=true e___name t____XML e___definition t____eXtensible Markup Language. e___update a____date=2002-12-23 w__word a___symbol=true e___name t____< e___definition t____Mathematical symbol representing the "less than" logical operation, like: 1<2. e___definition t____Reserved symbol in XML representing the beginning of tags, like: t____<p>Hello world!</p>
Note that:
Last update: 2014.
Table of Contents
Introduction of XML (eXtensible Markup Language)
DOM (Document Object Model) Programming Interface
SAX (Simple API for XML) Programming Interface
DTD (Document Type Definition) Introduction
Validating an XML Document against the Specified DTD Document Type
XSD (XML Schema Definition) Introduction
Validating XML Documents Against Specified XML Schemas
XSL (Extensible Stylesheet Language) Introduction
XSLT (XSL Transformations) Introduction
►XSLT Elements as Programming Statements
"value-of" - Evaluating XPath String Expressions
Examples of Using "value-of" Elements
"{expression}" - Shorthand of "value-of" Elements
"variable" - Declaring Variables
"for-each" - Looping through a Node Set
►Examples of Using "for-each" Elements
"if" - The Conditional Element
"choose" - The If...Else Element
Control and Generate XML Element in the Result
XML Tools Plugin for Notepad++