2012-05-05 50 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