XSL使用备用命名空间在XML内部转换HTML

时间:2013-01-11 00:20:56

标签: html xml xslt

使用浏览器,我希望使用XSL样式表转换可能包含某些HTML的XML。 在this article中,用户Mads Hansen写道:

  

如果您的HTML格式正确,那么只需嵌入HTML标记而不转义或换行   在CDTATA。如果可能的话,将内容保存在XML中会有所帮助。它会给你更多   转换和操作文档的灵活性。   您可以为HTML设置命名空间,以便您可以消除歧义   来自其他XML的HTML标记包装它。

我喜欢提出的解决方案,但无法使其发挥作用。我使用h作为html的命名空间:

temp.xml

<?xml version='1.0' encoding='UTF-8' ?>
<?xml-stylesheet type='text/xsl' href='temp.xsl'?>
<root xmlns:h="http://www.w3.org/1999/xhtml">
  <MYTAG title="thisnthat">
    text before ol
    <h:ol>
      <h:li>item</h:li>
      <h:li>item</h:li>
    </h:ol>
    text after ol
  </MYTAG>
</root>

temp.xsl

<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:h="http://www.w3.org/1999/xhtml">
  <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="/root">
    <html lang="en-US">
      <head>
        <meta charset="UTF-8" />
        <title></title>
      </head>
      <body>
        <xsl:apply-templates />
      </body>
    </html>
  </xsl:template>
  <xsl:template match="MYTAG">
    <h3>
      <xsl:value-of select="@title" />
    </h3>
    <xsl:apply-templates />
  </xsl:template>
</xsl:stylesheet>

输出(来自Firefox 18)是:

thisnthat
text before ol item item text after ol 

1 个答案:

答案 0 :(得分:0)

由于您正在生成最终的HTML并且处于控制之下,因此我不确定您为什么要在此处使用命名空间。只有当您的自定义标记与标准HTML之间存在冲突时,您才需要这样做 - 即,如果您的自定义<a...>标记与HTML具有不同的语义。

让我的转变工作

a)删除所有HTML命名空间

b)添加身份转换

<强>的test.xml

<?xml version='1.0' encoding='UTF-8' ?>
<?xml-stylesheet type='text/xsl' href='test.xsl'?>
<root>
    <MYTAG title="thisnthat">
        text before ol
        <ol>
            <li>item</li>
            <li>item</li>
        </ol>
        text after ol
    </MYTAG>
</root>

<强> test.xsl

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" encoding="UTF-8" indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/root">
        <html lang="en-US">
            <head>
                <meta charset="UTF-8" />
                <title></title>
            </head>
            <body>
                <xsl:apply-templates />
            </body>
        </html>
    </xsl:template>
    <xsl:template match="MYTAG">
        <h3>
            <xsl:value-of select="@title" />
        </h3>
        <xsl:apply-templates />
    </xsl:template>
</xsl:stylesheet>
相关问题