XSLT <value-of>
Extracting and displaying XML data values
📝 What is <xsl:value-of>?
The <xsl:value-of> element extracts the value of an XML node and displays it in the output. It's used to select and show specific data from your XML document.
<!-- Simple value-of example -->
<xsl:value-of select="title"/>
Understanding <value-of>
The <xsl:value-of> element is one of the most commonly used XSLT elements. It retrieves text content from XML nodes using XPath expressions and inserts it into the transformed output document.
Select Attribute
Points to the XML node
<xsl:value-of select="name"/>
XPath Expression
Navigate XML structure
<xsl:value-of select="book/title"/>
Text Output
Displays node content
<xsl:value-of select="@price"/>
Single Value
Returns first match only
<xsl:value-of select="item[1]"/>
🔹 Basic Example
Here's a simple example showing how to extract values from XML:
XML Data:
<?xml version="1.0"?>
<book>
<title>Learning XSLT</title>
<author>John Smith</author>
<price>29.99</price>
</book>
XSLT Template:
<xsl:template match="book">
<h2><xsl:value-of select="title"/></h2>
<p>Author: <xsl:value-of select="author"/></p>
<p>Price: $<xsl:value-of select="price"/></p>
</xsl:template>
Output:
Learning XSLT
Author: John Smith
Price: $29.99
🔹 Selecting Attributes
Use the @ symbol to select attribute values from XML elements:
XML Data:
<product id="101" category="Electronics">
<name>Laptop</name>
</product>
XSLT Template:
<xsl:template match="product">
<p>ID: <xsl:value-of select="@id"/></p>
<p>Category: <xsl:value-of select="@category"/></p>
<p>Name: <xsl:value-of select="name"/></p>
</xsl:template>
Output:
ID: 101
Category: Electronics
Name: Laptop
🔹 Using XPath Expressions
Navigate through nested XML structures using path expressions:
XML Data:
<library>
<book>
<title>XML Basics</title>
<author>
<firstname>Jane</firstname>
<lastname>Doe</lastname>
</author>
</book>
</library>
XSLT Template:
<xsl:template match="library">
<h3><xsl:value-of select="book/title"/></h3>
<p>By: <xsl:value-of select="book/author/firstname"/>
<xsl:value-of select="book/author/lastname"/></p>
</xsl:template>
Output:
XML Basics
By: Jane Doe
🔹 Complete XSLT Document
Here's a full working XSLT stylesheet using value-of:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h1>Book Information</h1>
<xsl:apply-templates select="book"/>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<div>
<h2><xsl:value-of select="title"/></h2>
<p><xsl:value-of select="author"/></p>
</div>
</xsl:template>
</xsl:stylesheet>
💡 Key Points:
-
Use
selectattribute to specify which node to extract -
Use
@to select attribute values - Returns only the first matching node if multiple exist
- Outputs text content, not HTML tags
- Can be combined with literal text in output