XML-XSL-仅选择与条件匹配的第一个元素

XML-XSL-仅选择与条件匹配的第一个元素,xml,xslt,xpath,xslt-1.0,xpath-1.0,Xml,Xslt,Xpath,Xslt 1.0,Xpath 1.0,假设我有一个MyObject元素的数组,它有一些属性,比如说IsFinalResult,我想根据它有条件地选择项。 我希望该逻辑只从数组中获取与给定条件匹配的第一个元素IsFinalResult==true(即使乘法元素与条件匹配) //这只会匹配一次 我只能使用XPath 1.0来实现这一点。您可以使用position()函数来实现这一点 <xsl:when test="position() = 1 and IsFinalResult='true'"> // this w

假设我有一个MyObject元素的数组,它有一些属性,比如说IsFinalResult,我想根据它有条件地选择项。 我希望该逻辑只从数组中获取与给定条件匹配的第一个元素IsFinalResult==true(即使乘法元素与条件匹配)


//这只会匹配一次

我只能使用XPath 1.0来实现这一点。

您可以使用
position()
函数来实现这一点

<xsl:when test="position() = 1 and IsFinalResult='true'">
   // this will match only once
</xsl:when>

您可以使用
position()
函数执行此操作

<xsl:when test="position() = 1 and IsFinalResult='true'">
   // this will match only once
</xsl:when>

考虑使用模板方法

<xsl:template match="/">
  <xsl:apply-templates select="ArrayOfMyObject/MyObject" />
</xsl:template>
(注意,我假设这里的
IsFinalResult
是一个属性。如果不是,只需删除
@
前缀)

要表示您的
xsl:otherly
,请使用一个模板(优先级较低),该模板将拾取所有其他
MyObject
元素

<xsl:template match="MyObject">

考虑使用模板方法

<xsl:template match="/">
  <xsl:apply-templates select="ArrayOfMyObject/MyObject" />
</xsl:template>
(注意,我假设这里的
IsFinalResult
是一个属性。如果不是,只需删除
@
前缀)

要表示您的
xsl:otherly
,请使用一个模板(优先级较低),该模板将拾取所有其他
MyObject
元素

<xsl:template match="MyObject">

当你的条件匹配时,你到底想做什么?否则你想做什么?当你的条件匹配时,你到底想做什么,否则你想做什么?匹配条件的第一个元素(我认为这就是这个问题)和第一个元素之间有区别,如果它符合条件(我认为这就是你的答案所做的)。在符合条件的第一个元素(我认为这就是这个问题所涉及的)和符合条件的第一个元素(我认为这就是你的答案所做的)之间是有区别的。
<xsl:template match="/ArrayOfMyObject/MyObject[IsFinalResult = 'true'][position() > 1]">
  <!-- Matches all the other elements of the list of elements that satisfy the first predicate -->
  ...
<xsl:template match="/">
  <xsl:apply-templates select="ArrayOfMyObject/MyObject" />
</xsl:template>
<xsl:template match="MyObject[@IsFinalResult='true'][1]">
<xsl:template match="MyObject">
<ArrayOfMyObject>
    <MyObject IsFinalResult="false">1</MyObject>
    <MyObject IsFinalResult="false">2</MyObject>
    <MyObject IsFinalResult="true">3</MyObject>
    <MyObject IsFinalResult="false">4</MyObject>
    <MyObject IsFinalResult="true">5</MyObject>
    <MyObject IsFinalResult="true">6</MyObject>
</ArrayOfMyObject>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates select="ArrayOfMyObject/MyObject" />
  </xsl:template>

  <xsl:template match="MyObject[@IsFinalResult='true'][1]">
    <When>
      <xsl:value-of select="." />
    </When>
  </xsl:template>

  <xsl:template match="MyObject">
    <Otherwise>
      <xsl:value-of select="." />
    </Otherwise>
  </xsl:template>
</xsl:stylesheet>
<Otherwise>1</Otherwise>
<Otherwise>2</Otherwise>
<When>3</When>
<Otherwise>4</Otherwise>
<Otherwise>5</Otherwise>
<Otherwise>6</Otherwise>
<xsl:template match="MyObject[not(@IsFinalResult='true')]" />