【发布时间】:2021-12-14 16:08:29
【问题描述】:
我有一个样式表可以成功地转换一些 XML 数据。
(XML数据转换与问题无关,已在示例中删除)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output doctype-system="about:legacy-compat" method="html" />
<xsl:template match="/contact:contact">
<html>
<head>
<title>My Title</title>
<xsl:copy-of select="document('../header.xml')" />
</head>
<body id="page-top" class="modern">
[not relevant]
</body>
</html>
</xsl:template>
</xsl:stylesheet>
样式表包括以下行,我们想用它在输出中插入一个标题。我们可以完全控制标头,并且标头是格式良好的 XML。
<xsl:copy-of select="document('../header.xml')" />
标头由带有节点作为内容的head 标记组成,我们希望将节点插入到最终输出中。
<?xml version="1.0" encoding="UTF-8"?>
<head xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<meta name="description" content="" />
<meta name="author" content="" />
</head>
现在我们很接近了,但是我们的根 head 元素被包含了两次:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Title</title>
<head>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"></meta>
<meta name="description" content=""></meta>
<meta name="author" content=""></meta>
</head>
</head>
<body id="page-top" class="modern">
</body>
</html>
我们对这一行做了什么修改,以便只包括根节点head 的子节点,而不包括根节点本身:
<xsl:copy-of select="document('../header.xml')" />
产生如下所示的输出:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Title</title>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"></meta>
<meta name="description" content=""></meta>
<meta name="author" content=""></meta>
</head>
<body id="page-top" class="modern">
</body>
</html>
(类似的问题已经被问过很多次了,大多数答案都与 XSLT 处理器的自定义行为有关。我需要符合标准的 XSLT,可以在现代浏览器中运行)。
【问题讨论】: