2012-05-05 48 views
1

我有與它的價值需要,只要它的值爲零,要更新的特定屬性(身份識別碼)的文件。該文件看起來像這樣XSLT匹配模板更改屬性只是一次

<?xml version="1.0" encoding="UTF-8"?><Summary> 
<Section myId="0"> 
    <Section myId="0"> 
    <Para>...</Para> 
    </Section> 
    <Section myId="5"> 
    <Para>...</Para> 
    </Section> 
</Section> 
</Summary> 

我使用的模板,以便將其設置爲從調用程序通過一個唯一的ID匹配的屬性,身份識別碼,但我只是想匹配文檔中的屬性之一。任何值爲零的附加屬性都將通過傳遞不同的ID進行更新。 我的模板,我使用的是這個樣子的:

<xsl:template  match = '@myId[.="0"]'> 
    <xsl:attribute name = "{name()}"> 
    <xsl:value-of select = "$addValue"/> 
    </xsl:attribute> 
</xsl:template> 

值的addValue是從調用程序通過一個全局參數。 我已經搜索了一天中很大一部分的答案,但是我無法僅將該模板應用一次。輸出將使用addValue的內容替換myId值。 我嘗試過匹配'@myId [。「0」] [1]「,我嘗試使用position()函數進行匹配,但我的模板總是應用於所有myId爲零的屬性。

是否有可能適用的匹配模板只有一次?

+0

嘗試使用位於計數爲0的'之前'軸。 – 2012-05-05 02:02:05

回答

1

是否有可能適用的匹配模板只有一次?

  1. 無論模板施加或不取決於導致執行要選擇的模板中的xsl:apply-templates

  2. Additionaly,匹配模式可以在保證了模板匹配的文件只在一個特定節點的方式來指定。

這裏是你可以做什麼

<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="pNewIdValue" select="9999"/> 


<xsl:template match="node()|@*"> 
    <xsl:copy> 
    <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match= 
"Section 
    [@myId = 0 
    and 
    not((preceding::Section | ancestor::Section) 
       [@myId = 0] 
     ) 
    ]/@myId"> 
    <xsl:attribute name="myId"><xsl:value-of select="$pNewIdValue"/></xsl:attribute> 
</xsl:template> 
</xsl:stylesheet> 

當這種轉化應用到所提供的XML文檔

<Summary> 
    <Section myId="0"> 
     <Section myId="0"> 
      <Para>...</Para> 
     </Section> 
     <Section myId="5"> 
      <Para>...</Para> 
     </Section> 
    </Section> 
</Summary> 

想要的,正確的結果是製作:

<Summary> 
    <Section myId="9999"> 
     <Section myId="0"> 
     <Para>...</Para> 
     </Section> 
     <Section myId="5"> 
     <Para>...</Para> 
     </Section> 
    </Section> 
</Summary> 
+0

前'不包含'ancestor',還是我缺少某些東西? – 2012-05-05 05:39:35

+0

@torazaburo:不,前後軸和祖先/後代軸是不重疊的。看到這個在W3C的XPath規格http://www.w3.org/TR/xpath/#axes子彈7和8 –

+0

@dimitre:我無法弄清楚如何使用前/宗軸與我的模板匹配屬性。也許這不可能,但你的解決方案正是我所需要的。非常感謝你的幫助!我在這裏學到了一些巧妙的匹配技巧。 – VEnglisch