客户端XSLT渲染不幸

时间:2016-03-10 18:58:05

标签: html css xslt safari

我有一种XML文档格式,随着时间的推移,它已经变成了一个简单的HTML包装器。为了帮助编辑(最终使用Coda的“预览”功能),我正在尝试进行XSLT翻译。

示例文件:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="x.xsl" type="text/xsl" ?>
<htmldocument>
  <title>Document Title</title>
  <section>
    <sectiontitle>Section Title</sectiontitle>
    <div>
        <p>First Paragraph</p>
        <p><b>Second Paragraph</b></p>      
    </div>
  </section>
</htmldocument>

我的XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/1999/xhtml">

  <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
  <xsl:template match="/htmldocument">
      <html>
          <head>
              <style type="text/css">
                  body
                  {
                      font-size: 15px;
                      font-family: Helvetica;
                  }
              </style>
          </head>
          <body>
              <xsl:apply-templates />
          </body>
      </html>
  </xsl:template>

  <xsl:template match="//title">
          <h1>
            <xsl:apply-templates />
          </h1>
  </xsl:template>   

  <xsl:template match="/htmldocument/section">
      <div>
        <xsl:apply-templates />
      </div>
  </xsl:template>

  <xsl:template match="/htmldocument/section/div">
      <xsl:copy-of select="." />
  </xsl:template>

  <xsl:template match="/htmldocument/section/sectiontitle">
      <h2>
        <xsl:apply-templates />
      </h2>
  </xsl:template>

</xsl:stylesheet>

如果我使用xsltproc将XML处理成HTML文件,一切都按预期工作:

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
                                  body
                                  {
                                          font-size: 15px;
                                          font-family: Helvetica;
                                  }
                          </style>
  </head>
  <body>
  <h1>Document Title</h1>
  <div>
    <h2>Section Title</h2>
    <div xmlns="">
            <p>First Paragraph</p>
            <p><b>Second Paragraph</b></p>
    </div>
  </div>
</body>
</html>

但是,如果我在浏览器中打开XML文件,虽然转换明显发生,但呈现HTML的显示很大程度上缺少任何样式信息。特别是,<div><p>似乎有display:inline,而<b>元素对字体权重没有影响。

我可以通过<style>元素添加额外的样式,但我真的不想重新发明轮子。

我在这里遗漏了什么,或者我只是期望客户端XSLT呈现过多?

1 个答案:

答案 0 :(得分:2)

您需要决定是否要在无命名空间中创建HTML输出,您可以在其中复制与HTML元素同名的无命名空间XML元素,或者是否需要XHTML输出以确保输入没有名称空间中的元素被转换为XHTML名称空间。

因此,要么删除XHTML名称空间并使用xsl:output method="html"/>,要么确保将XML中的元素转换为XHTML元素,例如(假设你保留xmlns="http://www.w3.org/1999/xhtml"

<xsl:template match="*">
  <xsl:element name="{local-name()}">
    <xsl:apply-templates select="@* | node()/">
  </xsl:element>
</xsl:template>