代码之家  ›  专栏  ›  技术社区  ›  D. Pardal

如何使用内部元素

  •  -1
  • D. Pardal  · 技术社区  · 8 年前

    我想用XML构建一个既可以保存文本又可以保存代码的文件,如下所示:

    <root>
        <item>Use the <code>location.href</code> propriety to change the URL.</item>
    <item>Something else.</item>
    </root>
    

    我想创建一个XSLT文件,将XML转换为HTML:

    <html>
        <body>
            <ul>
                <li>Use the <code>location.href</code> propriety to change the URL.</li>
                <li>Something else.</li>
            </ul>
        </body>
    </html>
    

    我尝试使用此XSLT代码,但它输出的HTML忽略了 <code> 标签它的内容仍然可见,但标签本身(及其格式)却无处可寻。

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
        <body>
            <ul>
                <xsl:for-each select="root/item">
                    <li><xsl:value-of select="." /></li>
                </xsl:for-each>
            </ul>
        </body>
        </html>
    </xsl:template>
    </xsl:stylesheet>
    

    我还尝试在XML文件中替换 <代码(>); 具有 &lt;code&gt; ,但结果是一样的。

    请告诉我怎么做。

    1 回复  |  直到 8 年前
        1
  •  1
  •   zx485 potemkin    8 年前

    您可以使用与 <item> s,然后使用 xsl:copy-of -复制所有子内容,而不是 xsl:value-of -它只复制文本内容。
    node() 选择所有节点(强调元素和文本节点)。

    <xsl:template match="/root">
        <html>
            <body>
                <ul>
                    <xsl:apply-templates />
                </ul>
            </body> 
        </html>
    </xsl:template>
    
    <xsl:template match="item">
        <li><xsl:copy-of select="node()" /></li>
    </xsl:template>
    

    输出符合要求。