如何在XSLT中处理嵌入式XML标记?

Cra*_*g W 13 html xml xslt formatting

我正在使用XSLT将XML转换为HTML.我无法弄清楚如何处理嵌入式XML节点的格式化.例如,假设我有XML元素:

<favoriteMovie>the <i>Star Wars</i> saga</favoriteMovie>

但是,在XLST期间,<i>标记会被忽略,因此"星球大战"在HTML输出中不是斜体.是否有一种相对简单的方法来解决这个问题?

的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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Dim*_*hev 11

但是,在XLST期间,<i>标记会被忽略,因此"星球大战"在HTML输出中不是斜体.是否有一种相对简单的方法来解决这个问题?

你的问题在这里:

<ul>
  <xsl:for-each select="favoriteMovies/favoriteMovie">
    <li><xsl:value-of select="."/></li>
  </xsl:for-each>
</ul>
Run Code Online (Sandbox Code Playgroud)

<xsl:value-of>指令用于创建文本节点.这样做时,它会select将此XSLT指令的属性中指定的XPath表达式的字符串值复制到输出.元素的字符串值是其所有文本节点后代的串联.

所以这就是你得到报告输出的方式.

方案:

使用该<xsl:copy-of>指令复制其select属性中指定的所有节点:

<ul>
  <xsl:for-each select="favoriteMovies/favoriteMovie">
    <li><xsl:copy-of select="node()"/></li>
  </xsl:for-each>
</ul>
Run Code Online (Sandbox Code Playgroud)

另一个更符合XSLT原则的解决方案可以避免使用<xsl:for-each>:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <html>
    <head />
    <body>
     <xsl:apply-templates/>
    </body>
  </html>
 </xsl:template>

 <xsl:template match="/*">
  <ul>
   <xsl:apply-templates/>
  </ul>
 </xsl:template>

 <xsl:template match="favoriteMovie">
  <li><xsl:copy-of select="node()"/></li>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当上面定义的两个解决方案中的任何一个应用于提供的XML文档时:

<favoriteMovies>
    <favoriteMovie>the 
        <i>Star Wars</i> saga
    </favoriteMovie>
</favoriteMovies>
Run Code Online (Sandbox Code Playgroud)

产生了想要的正确结果:

<html>
    <head/>
    <body>
        <ul>
            <li>the 
                <i>Star Wars</i> saga
            </li>
        </ul>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)