XSLT - match attribute
match
attribute is one of the most important parts of XSLT, because it controls which XML nodes a template applies to.
1. What match
Does
-
The
match
attribute of<xsl:template>
contains an XPath pattern. -
It tells the XSLT processor:
“This template applies whenever a node in the source XML matches this pattern.” -
Patterns can be broad (
match="*"
) or very specific (match="/library/book/title"
).
2. Basic Usage
<xsl:template match="book">
<!-- What to output when a <book> element is encountered -->
</xsl:template>
This template applies whenever the processor encounters a <book>
element in the XML.
3. Common Match Patterns
Pattern | Meaning |
---|---|
/ |
Matches the root node (the entire XML document). |
* |
Matches any element (wildcard). |
book |
Matches all <book> elements at any level. |
/library/book |
Matches <book> elements that are direct children of <library> . |
//book |
Matches all <book> elements anywhere in the document. |
book/title |
Matches <title> elements inside a <book> . |
@id |
Matches attributes named id . |
@* |
Matches any attribute. |
text() |
Matches text nodes (the actual text content inside elements). |
4. Example
XML:
<library>
<book id="b1">
<title>1984</title>
<author>George Orwell</author>
</book>
<book id="b2">
<title>Brave New World</title>
<author>Aldous Huxley</author>
</book>
</library>
XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- Root template -->
<xsl:template match="/">
<html>
<body>
<h2>Library</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<!-- Match the <library> element -->
<xsl:template match="library">
<ul>
<xsl:apply-templates/>
</ul>
</xsl:template>
<!-- Match <book> elements -->
<xsl:template match="book">
<li>
<xsl:value-of select="title"/>
(<xsl:value-of select="author"/>)
</li>
</xsl:template>
</xsl:stylesheet>
Output:
<html>
<body>
<h2>Library</h2>
<ul>
<li>1984 (George Orwell)</li>
<li>Brave New World (Aldous Huxley)</li>
</ul>
</body>
</html>
5. Match Precedence
-
If two templates could match the same node, the most specific one wins.
-
Example:
<xsl:template match="book"> ... </xsl:template> <xsl:template match="library/book"> ... </xsl:template>
-
For
<book>
inside<library>
, the second template (library/book
) will apply because it’s more specific.
-
6. Key Takeaways
-
match="/"
→ starting point (root). -
match="elementName"
→ handles specific elements. -
match="@attrName"
→ handles attributes. -
match="*"
or@*
→ wildcard patterns. -
More specific patterns override general ones.
.