2016-09-27 96 views
0

是否可以用apply-statement替換以下stylesheet中的呼叫模板語句?這樣模板的結構幾乎相同。結構的意思是我有一個xpath從源xml中選擇一個元素,例如/shiporder/address/city,我的輸出xml有一個目標xpath,例如/root/Address/Country然後我通過源路徑反轉。全部/shiporder/address/city歸入Country全部/shiporder/address歸入Address並且根shiporder變成標籤root使用應用模板而不是呼叫模板

源XML:

<shiporder> 
    <shipto>orderperson1</shipto> 
    <shipfrom>orderperson2</shipfrom> 
    <address> 
    <city>London</city> 
    </address> 
    <address> 
    <city>Berlin</city> 
    </address> 
</shiporder> 

樣式表:

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

<xsl:template match="/shiporder"> 
    <root> 
     <xsl:apply-templates select="address/city"/> 
     <xsl:call-template name="Identity" /> 
    </root> 
</xsl:template> 


<xsl:template name="Identity"> 
    <Identity> 
     <xsl:call-template name="Name" /> 
    </Identity> 
</xsl:template> 

<xsl:template name="Name"> 
    <Name> 
     <xsl:apply-templates select="/shiporder/shipto"/> 
    </Name> 
</xsl:template> 

<xsl:template match="/shiporder/shipto"> 
    <Last> 
     <xsl:apply-templates select="text()"/> 
    </Last> 
</xsl:template> 


<xsl:template match="/shiporder/address/city"> 
    <Country> 
     <xsl:apply-templates select="text()"/> 
    </Country> 
</xsl:template> 
+0

你能解釋一下爲什麼你選擇首先使用''? – Tomalak

+0

我不明白你的問題。我想用apply而不是call。 – StellaMaris

+0

我知道。我想了解你爲什麼使用「呼叫」,以便我可以幫助澄清你的思維錯誤。 – Tomalak

回答

1

一般來說,<xsl:call-template name="..."/>可以變成一個<xsl:apply-templates select="current()" mode="..."/><xsl:template match="node()" mode="..."/>(如只要這種模式不在其他地方使用)。

但在那裏,upvoted的答案是更合適的方式。

2

您可以使用以下方法:

<?xml version="1.0" encoding="UTF-8" ?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/shiporder"> 
     <root> 
      <xsl:apply-templates select="address/city"/> 
      <xsl:apply-templates select="shipto"/> 
     </root> 
    </xsl:template> 

    <xsl:template match="shipto"> 
     <Identity> 
      <Name> 
       <Last><xsl:value-of select="."/></Last> 
      </Name> 
     </Identity> 
    </xsl:template> 

    <xsl:template match="/shiporder/address/city"> 
     <Country> 
      <xsl:value-of select="."/> 
     </Country> 
    </xsl:template> 

</xsl:stylesheet> 
+0

我也有這個解決方案,但這不是一個選項,因爲'身份證'模板可能看起來像' ' – StellaMaris