如何获取前2个节点以前的特定节点?

问题描述 投票:0回答:1

这是我的xml:

<Line>
    <Item>
     <Id>1</Id>
     <Name>A</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>2</Id>
     <Name>B</Name>
     <Unit>Test</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>3</Id>
     <Name>C</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>4</Id>
     <Name>D</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>5</Id>
     <Name>E</Name>
     <Unit>AA</Unit>
      <Value>5</Value>
    </Item>
</Line>

如何在Unit = Test的节点之后得到位于第一和第二位置的所有节点。在这种情况下,Id = 2的节点具有Unit = Test,所以我想显示Id = 3和Id = 4的节点。谢谢

xslt
1个回答
1
投票

你想要的表达是......

<xsl:copy-of select="//Line[Item/Unit='Test']/following-sibling::Line[position() &lt;= 2]" />

无论当前节点是什么,这都将起作用。

或者,您可以将其拆分为模板。例如

<xsl:template match="/*">
  <xsl:apply-templates select="//Line[Item/Unit='Test']" />
</xsl:template>

<xsl:template match="Line">
  <xsl:copy-of select="following-sibling::Line[position() &lt;= 2]" />
</xsl:template>  

如果要获取除3和4之外的所有节点,请尝试使用此表达式

<xsl:copy-of select="//Line[not(preceding-sibling::Line[position() &lt;= 2][Item/Unit = 'Test'])]" />
© www.soinside.com 2019 - 2024. All rights reserved.