2011-04-11 62 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