【问题标题】:Converting HTML to XML using XSLT使用 XSLT 将 HTML 转换为 XML
【发布时间】:2013-05-23 10:42:43
【问题描述】:

我正在尝试使用 XSLT 将 XHTML 文档转换为 XML,但我目前无法让我的模板与输入文档中的标签匹配。我应该能够像这样将 XHTML 转换为 XML 吗?如果是这样,我的样式表中是否有错误?

输入文档:

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>      
        <title>title text</title>       
    </head>
    <body>      
        <p>body text</p>
    </body>
</html>

样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes" />


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



    <xsl:template match="html/head">
        <head><xsl:text>This is where all the metadata will come from</xsl:text></head>
    </xsl:template> 
</xsl:stylesheet>

预期输出

<article>       
  <head>This is where all the metadata will come from</head>        
</article>

谢谢

【问题讨论】:

    标签: xml xslt xhtml


    【解决方案1】:

    XHTML 文档中的元素位于http://www.w3.org/1999/xhtml 命名空间中。而您的 XSLT 文档正在匹配没有名称空间的元素。您需要添加一个命名空间,如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:xhtml="http://www.idpf.org/2007/opf">
    
        ...
        <xsl:template match="xhtml:html/xhtml:head">
            <head><xsl:text>This is where all the metadata will come from</xsl:text></head>
        </xsl:template> 
    </xsl:stylesheet>
    

    【讨论】:

    • 谢谢,成功了。我没有意识到我需要在转换中使用命名空间,因为输入文档中的标签没有使用像 这样的命名空间显式声明
    • 你并不孤单。几乎每天都有人问这个问题。
    猜你喜欢
    • 2014-03-08
    • 2012-09-29
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多