使用 XSLT 将 HTML 转换为 XML [英] Converting HTML to XML using XSLT

查看:38
本文介绍了使用 XSLT 将 HTML 转换为 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

输入文档:

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

谢谢

推荐答案

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

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>

这篇关于使用 XSLT 将 HTML 转换为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆