代码之家  ›  专栏  ›  技术社区  ›  Jon W

选择具有默认命名空间的节点

  •  1
  • Jon W  · 技术社区  · 17 年前

    我有一个使用了许多不同名称空间的XML文档和一个要验证的模式。模式要求所有元素都是“限定的”,我假设这意味着它们需要有完整的QName,而不需要空名称空间。

    我正在尝试编写一个XSLT,它将选择没有名称空间的节点,并为它们指定一个前缀与其他节点相同的特定节点。例如:

    <x:doc xmlns:x="http://thisns.com/">
      <x:node @x:property="true">
         this part passes validation
      </x:node>
      <node property="false">
         this part does not pass validation
      </node>
    </x:doc>
    

    我试着加上 xmlns="http://thisns.com/" 指向文档的根节点,但这与模式验证器不一致。你有没有想过我该怎么做?

    谢谢

    1 回复  |  直到 17 年前
        1
  •  3
  •   ckarras    17 年前
    <!-- Identity transform by default -->
    <xsl:template match="node() | @*">
      <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
      </xsl:copy>
    </xsl:template>
    <!-- Override identity transform for elements with blank namespace -->
    <xsl:template match="*[namespace-uri() = '']">    
      <xsl:element name="{local-name()}" namespace="http://thisns.com/">
        <xsl:apply-templates select="node() | @*"/>
      </xsl:element>
    </xsl:template>
    <!-- Override identity transform for attributes with blank namespace -->
    <xsl:template match="@*[namespace-uri() = '']">
      <xsl:attribute name="{local-name()}" namespace="http://thisns.com/"><xsl:value-of  select="."/></xsl:attribute>
    </xsl:template>
    

    这将产生与以下类似的结果:

    <x:doc xmlns:x="http://thisns.com/">
      <x:node x:property="true">
        this part passes validation
      </x:node>
      <node xp_0:property="false" xmlns="http://thisns.com/" xmlns:xp_0="http://thisns.com/">
         this part does not pass validation
      </node>
    </x:doc>
    

    请注意,第二个<节点>仍然没有名称空间前缀,但由于xmlns=属性,它现在被视为同一名称空间的一部分。