How to pick value of multiple nodes and test it in a single condition?

给你一囗甜甜゛ 提交于 2021-02-11 06:51:31

问题


In continuation to this post, I have restructured the code to better understand my requirement. I have also provided more detail to it.

XML FILE

<Person>
  <Name>Kavya</Name>
  <Gift>
    <ItemName>PD1</ItemName>
  </Gift>
  <Gift>
    <ItemName>PS1</ItemName>
  </Gift>
  <Gift>
    <ItemName>PD2</ItemName>
  </Gift>
</Person>

Now, In the above structure, I need to return a text Successfull only when the Person has a Gift with ItemName that is empty or has only PS1 and not PD1 or PD2. So, when writing an XSLT file, I used the below approach:

XSLT File ( Example )

<Test>
  <xsl:choose>
    <xsl:when test="//Person/Gift[ItemName='PS1' and ItemName!='PD1']">
      <xsl:text>Successfull</xsl:text>
    </xsl:when>
  </xsl:choose>
</Test>

As of now, it returns Successfull, since one of the Gifts has ItemName as 'PS1'. But, according to my need, it must not display anything since, although there is an ItemName as 'PS1', the person yet has gifts with ItemName as 'PD1' and 'PD2'

To be precise, I don't want to check individual ItemName in Gift. I am trying to check if the Person ( as a whole ) has PS1 and not PD1 or PD2

Hoping this is clear. Kindly assist.


回答1:


In XSLT 2.0, you could use exists():

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/Person">
    <xsl:choose>
      <xsl:when test="./Gift[ItemName='PS1'] and not(exists(./Gift[ItemName='PD1']))">
        <xsl:text>Sample</xsl:text>
      </xsl:when>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>


来源:https://stackoverflow.com/questions/66132681/how-to-pick-value-of-multiple-nodes-and-test-it-in-a-single-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!