使用XSLT将HTML转换为XML

Jim*_*imS 3 xml xslt xhtml

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

样式表:

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

预期产出

<article>       
  <head>This is where all the metadata will come from</head>        
</article>
Run Code Online (Sandbox Code Playgroud)

谢谢

Col*_*inE 5

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

  • 你不是一个人.有人几乎每天都会问这个问题. (2认同)