【发布时间】:2011-07-21 22:56:38
【问题描述】:
我正在尝试使用 xslt 转换 .html 文档。由于某种原因,生成的 html 在 head 元素上有一个额外的 xmlns 属性,而在 title 元素上有一个空的 xmlns 属性。
example.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>foo</title></head>
<body><h1>bar</h1><img src="baz.jpg" /></body>
</html>
模板.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:output doctype-system="about:legacy-compat" method="html"
omit-xml-declaration="yes" />
<xsl:template match="/html/head">
<head>
<meta name="description" content="something added to the head element"/>
<xsl:apply-templates select="./@*|./node()" />
</head>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我一直在用 xsltproc 和 php 测试转换。
运行 xsltproc:
$ xsltproc -html template.xsl example.html
<!DOCTYPE html SYSTEM "about:legacy-compat">
<html xmlns="http://www.w3.org/1999/xhtml">
<head xmlns="http://www.w3.org/1999/xhtml"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="description" content="something added to the head element"></meta><title xmlns="">foo</title></head><body>
<h1>bar</h1>
<img src="baz.jpg">
</body>
</html>
使用 PHP:
<?php
$xmldoc = new DomDocument ();
$xmldoc->loadHTMLFile ("example.html");
$xsldoc = new DomDocument ();
$xsldoc->load ("template.xsl");
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsldoc);
echo $xslt->transformToXML ($xmldoc);
我希望源文档中的所有元素都在 html 命名空间中,所以我不明白为什么 apply-templates 似乎从标题元素中删除了命名空间。我也不明白为什么将html命名空间添加到head元素中。
【问题讨论】:
标签: html xslt xml-namespaces