Converting HTML to XML using XSLT

假如想象 提交于 2020-01-13 13:53:11

问题


I'm trying to convert an XHTML document to XML using XSLT but I'm currently having trouble getting my templates to match the tags in the input document. Should I be able to convert XHTML to XML like this? If so is there an error in my stylesheet?

Input Document:

<?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>

Stylesheet:

<?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>

Expected Output

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

Thanks


回答1:


The elements within your XHTML document are in the http://www.w3.org/1999/xhtml namespace. Whereas your XSLT document is matching elements that do not have a namespace. You need to add a namespace as follows:

<?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>


来源:https://stackoverflow.com/questions/16711842/converting-html-to-xml-using-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!