【问题标题】:How do I add a header to HTML being transformed by an XSLT stylesheet?如何将标题添加到由 XSLT 样式表转换的 HTML?
【发布时间】: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,可以在现代浏览器中运行)。

【问题讨论】:

    标签: html xml xslt


    【解决方案1】:

    试试:

    <xsl:copy-of select="document('../header.xml')/*/*" />
    

    严格来说,你应该将http://www.w3.org/1999/xhtml命名空间绑定到一个前缀,然后使用它——例如

    <xsl:copy-of select="document('../header.xml')/x:head/*" />
    

    但我不确定这是否值得。

    【讨论】:

    • document('../header.xml')/*/* 有效, document('../header.xml')/head/* 没有,即使命名空间相同。谢谢你!
    • 仔细看:我没有建议document('../header.xml')/head/*。我不确定您所说的“命名空间相同”是什么意思。处理输入时,输出的命名空间无关紧要。见:stackoverflow.com/a/34762628/3016153
    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 2013-02-13
    • 1970-01-01
    • 2017-11-06
    • 2016-08-23
    • 2023-01-30
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多