I am using XSLT to convert XML to HTML. I am having trouble figuring out how to deal with embedded XML nodes for formatting. For example, let’s say I have the XML element:
<favoriteMovie>the <i>Star Wars</i> saga</favoriteMovie>
However, during XLST, the <i> tag gets ignored, so “Star Wars” is not italicized in the HTML output. Is there a relatively simple way to fix this?
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="test.html.xsl"?>
<favoriteMovies>
<favoriteMovie>the <i>Star Wars</i> saga</favoriteMovie>
</favoriteMovies>
test.html.xsl:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes" />
<xsl:template match="/">
<html>
<head />
<body>
<ul>
<xsl:for-each select="favoriteMovies/favoriteMovie">
<li><xsl:value-of select="." /></li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Your problem is here:
The
<xsl:value-of>instruction is used to create a text node. In doing so it copies to the output the string value of the XPath expression specified in theselectattribute of this XSLT instruction. The string value of an element is the concatenation of all its text-node descendents.So this is how you get the reported output.
Solution:
Use the
<xsl:copy-of>instruction, which copies all the nodes that are specified in itsselectattribute:Another solution, more alligned with the principles of XSLT avoids using
<xsl:for-each>at all:When any of the two solutions defined above are applied to the provided XML document:
the wanted, correct result is produced: