Let's explain <xsl:value-of>
in XML and XSLT with a simple example:
XML is a markup language used to structure and store data. It consists of elements that define the hierarchical structure of the data.
XSLT is a language for transforming XML documents into different formats, such as HTML, XML, or plain text. It uses templates and instructions to define how the transformation should occur.
<xsl:value-of>
in XSLT:<xsl:value-of>
is an XSLT instruction used to extract the value of a selected node or expression from the input XML document. It retrieves the text content of the selected node and includes it in the output of the transformation.
Let's say we have an XML document representing a book:
Example
<?xml version="1.0" encoding="UTF-8"?> <book> <title>Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> </book>
Now, suppose we want to use XSLT to transform this XML into an HTML paragraph (<p>
) that displays the title and author of the book.
Here's how you can use <xsl:value-of>
to achieve this transformation:
Example
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Template to match the root element --> <xsl:template match="/"> <html> <body> <h2>Book Information</h2> <p> Title: <xsl:value-of select="book/title"/><br/> Author: <xsl:value-of select="book/author"/> </p> </body> </html> </xsl:template> </xsl:stylesheet>
XSLT Structure:
<xsl:stylesheet>
defines the XSLT document with its version and namespace.xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
declares the XSLT namespace.Template and <xsl:value-of>
Usage:
<xsl:template match="/">
: This template matches the root element of the XML document (/
). It defines the structure of the HTML output.<xsl:value-of select="book/title"/>
retrieves the text content of the <title>
element within the <book>
element.<xsl:value-of select="book/author"/>
retrieves the text content of the <author>
element within the <book>
element.When this XSLT transformation is applied to the XML document provided earlier, the output HTML will be:
Example
<html> <body> <h2>Book Information</h2> <p> Title: Harry Potter<br/> Author: J.K. Rowling </p> </body> </html>
<xsl:value-of>
retrieves the text content of a selected node or expression in the XML document and includes it in the output of the transformation.In this example, <xsl:value-of>
was used to extract and display specific data from an XML document, demonstrating its utility in transforming XML data into structured output formats like HTML