2011-12-18 155 views
2

我已經寫在需要模板名稱適用於在一個XSLT一個XML文件,C#的應用程序。XSLT選擇模板

示例XML:

<Data> 
    <Person> 
     <Name>bob</Name> 
     <Age>43</Age> 
    </Person> 
    <Thing> 
     <Color>Red</Color> 
    </Thing> 
</Data> 

示例XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"> 

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

    <xsl:param name="TargetName" /> 
    <xsl:param name="RootPath" /> 

    <xsl:Template Name="AgeGrabber"> 
     <xsl:value-of select="/Person/Age" /> 
    </xsl:Template> 

    <xsl:Template Name="ColorGrabber"> 
     <xsl:value-of select="/Color" /> 
    </xsl:Template> 

</xsl:stylesheet> 

說我想與路徑運行模板 「ColorGrabber」 「/數據/事」,然後運行與模板的另一個變換帶有路徑「/ Data」的「AgeGrabber」。這可能嗎?我想我可以在路徑和模板名稱(hense頂部的2個PARAMS),然後做一些類型的開關通過,但它看起來像XSL:呼叫模板不能拿一個參數的name屬性。

我怎樣才能實現這種行爲?

+1

轉換的預期輸出到底是什麼? – mzjn 2011-12-18 11:06:19

回答

1

有許多問題這個問題:指定

  1. <xsl:stylesheet version="2.0" ...,然而,目前> NET本身不支持XSLT 2.0。

  2. 例如規範和導出代碼是不是太有意義,因爲單個XML文檔不能同時包含/Person/Age/Color元素 - 一個簡潔(wellformed)的XML文檔僅具有單個頂部元件和它可以是PersonColor,但不能同時使用。

萬一有一個更有意義的例子

<Person> 
<Age>27</Age> 
<HairColor>blond</HairColor> 
</Person> 

一個簡單的解決方案是

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:param name="pProperty" select="'Age'"/> 

<xsl:template match="/"> 
    <xsl:value-of select="/*/*[name()=$pProperty]"/> 
</xsl:template> 
</xsl:stylesheet> 

,並且當該變換被施加在上面的XML文檔它產生了想要的結果:

27 

如果感興趣的元素的嵌套結構可以是任意的和/或我們需要在不同的元素做不同的處理,然後適當的解決方案是使用匹配模板(未命名的):

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

<xsl:param name="pProperty" select="'HairColor'"/> 

<xsl:template match="Age"> 
    <xsl:if test="$pProperty = 'Age'"> 
    This person is <xsl:value-of select="."/> old. 
    </xsl:if> 
</xsl:template> 

<xsl:template match="HairColor"> 
    <xsl:if test="$pProperty = 'HairColor'"> 
    This person has <xsl:value-of select="."/> hair. 
    </xsl:if> 
</xsl:template> 
</xsl:stylesheet> 

當這種轉化是在同一個XML文檔(以上)應用,再次正確的結果產生

This person has blond hair. 

最後,如果你真的想在XSLT 1.0或XSLT 2.0模擬高階函數(HOF),看到這樣的回答:https://stackoverflow.com/a/8363249/36305,或瞭解FXSL

0

簡單多了:準備兩個應用的模板規則(年齡和色彩元素)和有條件地發送適當的節點進行改造 -//人/年齡或/ /事/彩色

0

你猜對了倒退。你應該創建模板,匹配你想要使用的節點。

<xsl:stylesheet> 
    <xsl:template match="Person|Thing"> 
     <xsl:apply-templates /> 
    </xsl:template> 

    <xsl:template match="Person"> 
     <xsl:value-of select="Age" /> 
    </xsl:template> 

    <xsl:template match="Thing"> 
     <xsl:value-of select="Color" /> 
    </xsl:template> 

</xsl:stylesheet>