2012-08-22 40 views
18

這兩個模板之間有什麼區別?XSLT中*和node()之間的區別

<xsl:template match="node()"> 

<xsl:template match="*"> 
+0

這個答案也是適用的:http://stackoverflow.com/questions/5394178/difference-between-childnode-and-child – StuartLC

回答

30
<xsl:template match="node()"> 

爲的縮寫:

<xsl:template match="child::node()"> 

這可以經由the child::來選擇任何節點類型匹配:

  • 元件

  • 文本節點

  • 處理指令(PI)節點

  • 註釋節點。

在另一側

<xsl:template match="*"> 

爲的縮寫:

<xsl:template match="child::*"> 

此任何元件匹配。

XPath表達式:someAxis :: *匹配給定軸的主節點類型的任何節點。

對於child::軸,主要節點類型是元件

12

只是爲了說明的區別之一,即是*不匹配text

給定的XML:

<A> 
    Text1 
    <B/> 
    Text2 
</A> 

匹配上node()

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> 

    <!--Suppress unmatched text--> 
    <xsl:template match="text()" /> 

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

    <xsl:template match="node()"> 
     <node> 
      <xsl:copy /> 
     </node> 
     <xsl:apply-templates /> 
    </xsl:template> 
</xsl:stylesheet> 

給出:

<root> 
    <node> 
     <A /> 
    </node> 
    <node> 
     Text1 
    </node> 
    <node> 
     <B /> 
    </node> 
    <node> 
     Text2 
    </node> 
</root> 

而匹配上*

<xsl:template match="*"> 
    <star> 
     <xsl:copy /> 
    </star> 
    <xsl:apply-templates /> 
</xsl:template> 

不匹配文本節點。

<root> 
    <star> 
    <A /> 
    </star> 
    <star> 
    <B /> 
    </star> 
</root> 
+1

也不會匹配註釋節點,處理指令節點,屬性節點,命名空間節點和文檔節點...模式或表達式'*'(本身,如縮寫。爲'child :: *')**只匹配元素節點和元素節點**。當使用'@ *','attribute :: *'的縮寫時,星號與屬性軸上的_only_屬性節點相匹配。 – Abel