使用copy-of with document()将SVG添加到XHTML输出

时间:2013-08-30 21:05:26

标签: html xml svg xslt-1.0 xslt-2.0

在处理我的XML时,我正在尝试将从href属性引用的SVG文件直接复制到我的输出HTML中,其中包含以下行:

 <xsl:copy-of copy-namespaces="yes" select="document(@href)"/>

copy-namespaces不应该是必要的,因为无论如何默认值是“是”,但我已经添加它以防止我是否尝试过它。

将文件复制到HTML中,但任何命名空间元素都会被清除。例如,在复制之前看起来像这样的文件:

  <rdf:RDF>
      <cc:Work rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
        <dc:title/>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g transform="translate(-519.21143,-667.79077)" id="layer1">
    <image xlink:href="data:image/png;base64

之后看起来像这样:

  <_0:RDF xmlns:_0="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <_0:Work xmlns:_0="http://creativecommons.org/ns#" about="">
        <_0:format xmlns:_0="http://purl.org/dc/elements/1.1/">image/svg+xml</_0:format>
        <_0:type xmlns:_0="http://purl.org/dc/elements/1.1/" resource="http://purl.org/dc/dcmitype/StillImage"/>
        <_0:title xmlns:_0="http://purl.org/dc/elements/1.1/"/>
      </_0:Work>
    </_0:RDF>
  </metadata>
  <g id="layer1" transform="translate(-519.21143,-667.79077)">
    <image href="data:image/png;base64

图像元素的href值上缺少的xlink命名空间特别成问题。

关于如何以不同的方式阅读SVG文件而没有任何解释的任何想法?

我找到了一个“有效”的解决方案,但它是一个黑客,我想要更优雅的东西:

<xsl:template name="topic-image-svg">
    <!-- Generate tags to embed SWFs -->
    <xsl:element name="div">
      <xsl:if test="@width">
        <xsl:attribute name="width">
          <xsl:value-of select="@width"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:if test="@height">
        <xsl:attribute name="height">
          <xsl:value-of select="@height"/>
        </xsl:attribute>
      </xsl:if>     
        <xsl:apply-templates select="document(@href)" mode="svg"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="*" mode="svg">
    <xsl:copy copy-namespaces="yes">
      <xsl:for-each select="@*">
        <xsl:choose>
          <xsl:when test="self::node()[name() = 'xlink:href']">
            <xsl:attribute name="xlink:href"><xsl:value-of select="."></xsl:value-of></xsl:attribute>
          </xsl:when>
          <xsl:otherwise>
            <xsl:copy></xsl:copy>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:for-each>
     <xsl:apply-templates mode="svg"></xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

1 个答案:

答案 0 :(得分:1)

我认为你已经找到了这个XSLT操作的原因:

http://www.w3schools.com/xsl/el_namespace-alias.asp

,在完成命名空间转换之前,在生成输出之前,将损坏的命名空间保持不变。