xsl 属性命名空间

Ole*_*liv 2 xslt

我有以下xml

<?xml version="1.0" encoding="UTF-8"?>
<content>
  <artwork classification="12" href="1.jpg"/>
  <artwork classification="10" href="2.jpg"/>
</content>
Run Code Online (Sandbox Code Playgroud)

应用 xsl 时

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                >

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@href">
    <xsl:attribute name="xlink:href">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

它产生

<?xml version="1.0" encoding="UTF-8"?>
<content>
  <artwork classification="12" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="1.jpg"/>
  <artwork classification="10" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="2.jpg"/>
</content>
Run Code Online (Sandbox Code Playgroud)

而我需要

<?xml version="1.0" encoding="UTF-8"?>
<content xmlns:xlink="http://www.w3.org/1999/xlink">
  <artwork classification="12"  xlink:href="1.jpg"/>
  <artwork classification="10"  xlink:href="2.jpg"/>
</content>
Run Code Online (Sandbox Code Playgroud)

我应该如何修改我的 xsl 以获得我需要的结果?

我使用 xalan XSLT 处理器。

Emi*_*ggi 5

您只需要匹配要为其声明命名空间的元素。处理器将为您应用命名空间。


XSLT 1.0在MSXSL 4.0下测试(也在Saxon-HE 9.2.1.1J下作为XSLT 2.0测试)

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    >

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="content">
        <content>
            <xsl:apply-templates select="@*|node()"/>
        </content>
    </xsl:template>

    <xsl:template match="@href">
        <xsl:attribute name="xlink:href">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这样做的原因是文字结果元素 (`&lt;content&gt;`) 获取样式表中声明的所有范围内命名空间的副本,而使用 `xsl:copy` 生成的元素不会。 (6认同)