How to display mixed XML content in HTML using XSLT?
XML content is mixed when text and attributes are both present inside an element. The
<title> element has mixed content in the following example.
Create an XML document.
<?xml version="1.0"?>
<books>
<book>
<title ISBN="0321173481" author="Michael R. Sweet">
OpenGL Programming Guide Fourth Edition</title>
<publisher>Addison-Wesley</publisher>
<year>2004</year>
</book>
<book>
<title ISBN="0849371643" author="Gerald Farin">
Curves and Surfaces for CAGD: A Practical Guide</title>
<publisher>Academic Press</publisher>
<year>2002</year>
</book>
<book>
<title ISBN="1558606696" author="David Rogers">
An Introduction to NURBS: With Historical Perspective</title>
<publisher>Academic Press</publisher>
<year>2001</year>
</book>
<book>
<title ISBN="1568810849" author="Gerald Farin">
NURBS: From Projective Geometry to Practical Use</title>
<publisher>A K Peters</publisher>
<year>1999</year>
</book>
</books>
Create the XSL stylesheet.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<xsl:template match="/">
<html>
<head><title>Books</title>
</head>
<body>
<table width="100%" border="1">
<THEAD>
<TR>
<TD width="10%"><B>ISBN</B></TD>
<TD width="20%"><B>Author</B></TD>
<TD width="40%"><B>Title</B></TD>
<TD width="20%"><B>Publisher</B></TD>
<TD width="10%"><B>Year</B></TD>
</TR>
</THEAD>
<TBODY>
<xsl:for-each select="books/book">
<TR>
<xsl:apply-templates select="title" />
<TD width="40%"><xsl:value-of select="title" /></TD>
<TD width="20%"><xsl:value-of select="publisher" /></TD>
<TD width="10%"><xsl:value-of select="year" /></TD>
</TR>
</xsl:for-each>
</TBODY>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="title">
<TD width="10%"><xsl:value-of select="@ISBN" /></TD>
<TD width="20%"><xsl:value-of select="@author" /></TD>
</xsl:template>
</xsl:stylesheet>
Attributes are referred to in the same way as elements are. The difference being, attribute's names are prefixed by a
@ symbol.
<xsl:apply-templates select="title" />
This creates a new template to process further elements that start from the element specified.
<xsl:template match="title">
This matches all occurences of the specified element.
<xsl:value-of select="title" />
This outputs the text value of all
<title> elements found.
<xsl:value-of select="@ISBN" />
This outputs the attribute's value.
Back to
XML FAQ