2017-04-13 18 views
0

如何在下面的示例中顯示Hola?現在,它返回Hello。如果變量包含一組,那麼我該如何到達第二個項目

XML

<?xml version="1.0" encoding="utf-8"?> 
<?xml-stylesheet type="text/xsl" href="nodevariable.xslt"?> <!--todo: change this if copying to new file--> 
<!--todo: change preceding line if copying to new file--> 
<greetings> 
    <greeting id="1"> 
    <can> 
     <be> 
     <a> 
      <long itemNo="1"> 
      <path>Hello</path> 
      </long> 
      <long itemNo="2"> 
      <path>World</path> 
      </long> 
     </a> 
     </be> 
    </can> 
    </greeting> 
    <greeting id="2"> 
    <can> 
     <be> 
     <a> 
      <long itemNo="1"> 
      <path>Hola</path> 
      </long> 
      <long itemNo="2"> 
      <path>Mundo</path> 
      </long> 
     </a> 
     </be> 
    </can> 
    </greeting> 
</greetings> 

XSL

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

    <xsl:template match="greetings"> 
    <xsl:apply-templates select="greeting[@id &gt; 1]"/> 
    </xsl:template> 

    <xsl:variable name="testVar" select="/greetings/greeting/can/be/a/long[@itemNo=1]" /> 

    <xsl:template match="greeting"> 
    <html> 
     <body> 
     <h1> 
      <xsl:value-of select="$testVar/path"/> 
     </h1> 
     </body> 
    </html> 
    </xsl:template> 
</xsl:stylesheet> 

回答

1

您可以通過移動testVar聲明到您的模板,並用它相對於當前位置,做到這一點。

正如你所知,testVar只是簡單地評估爲所有有這條路徑的節點,其中有兩個。

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

    <xsl:template match="greetings"> 
    <xsl:apply-templates select="greeting[@id &gt; 1]"/> 
    </xsl:template> 

    <xsl:template match="greeting"> 
    <xsl:variable name="testVar" select="can/be/a/long[@itemNo=1]" /> 
    <html> 
     <body> 
     <h1> 
      <xsl:value-of select="$testVar/path"/> 
     </h1> 
     </body> 
    </html> 
    </xsl:template> 
</xsl:stylesheet> 

僅供參考,如果您要訪問的節點集的第二個項目,你可以使用[2]這樣做:$testVar[2]/path,但在你的例子這樣做會破壞使用模板的目的。

相關問題