2011-04-11 65 views
2

我正在使用XSL when子句將一個XML文件轉換爲另一個XML文件。我在測試時需要使用「存在」功能。在XSL中存在函數When Statement

下面是一個例子源XML:

<People> 
    <Person personid="1" location="US" fullname="John Doe"/> 
    <Person personid="2" location="US" fullname="Jane Doe"/> 
</People> 
<Nicknames> 
    <Nickname personid="1" nname="Johnny D"/> 
</Nicknames> 

這裏是我的例子XSL:

<xsl:element name="HASNICKNAME"> 
    <xsl:choose> 
     <!-- If nickname exists in source XML, return true --> 
     <xsl:when test="boolean exists function" 
     <xsl:text>TRUE</xsl:text> 
     </xsl:when> 
     <xsl:otherwise> 
     <xsl:text>FALSE</xsl:text> 
     </xsl:otherwise> 
    </xsl:choose> 
    </xsl:element> 

誰能幫與存在的一部分?

+0

的可能重複[檢查是否存在使用XSLT節點(http://stackoverflow.com/questions/4694480/check-if-a-node-exists-using-xslt) – 2011-04-11 21:50:33

+0

或http://stackoverflow.com/questions/767851/xpath-find-if-node-exists或http://stackoverflow.com/questions/4948878/xslt-detecting-if-a-node-exists或任何http://www.google.com/search?q=site%3Astackoverflow.com+xslt+exist+node – 2011-04-11 21:57:24

回答

2

假設變量$personid包含Person要檢查,那麼這隻能檢查存在的@personid

<xsl:when test="boolean(//Nickname[@personid=$personid]/@nname)"> 

對於類似的問題,我通常喜歡以檢查非空/非空白值:

<xsl:when test="normalize-space(//Nickname[@personid=$personid]/@nname)!=''"> 

如果你使用像<xsl:key name="nn" match="//Nickname" use="@personid"/>的關鍵,下面也是可能的:

<xsl:when test="normalize-space(key('nn',$personid)/@nname)!=''"> 

後者不需要$personid變量,但可以直接與Person要檢查的@personid工作...

+0

感謝mousio,我用過$ personId的變量方法,它的工作完美。 – cedarleaf 2011-04-12 01:36:04