简体   繁体   中英

How to get first occurrence in XML

I have XML data which has a structure like below. I need to fetch only first CX.1 value which CX.5 value starts with 'TN'

<PID.3.LST>
    <PID.3>
        <CX.1>432</CX.1>
        <CX.4>BH</CX.4>
        <CX.5>TN</CX.5>
        <CX.6>BH</CX.6>
    </PID.3>
    <PID.3>
        <CX.1>444</CX.1>
        <CX.4>BH</CX.4>
        <CX.5>TN</CX.5>
        <CX.6>BH</CX.6>
    </PID.3>
    <PID.3>
        <CX.1>8415</CX.1>
        <CX.4>SWH</CX.4>
        <CX.5>MR</CX.5>
        <CX.6>SWH</CX.6>
    </PID.3>
    <PID.3>
        <CX.1>915252936  </CX.1>
        <CX.2>9</CX.2>
        <CX.4>AUSHIC</CX.4>
        <CX.5>MC</CX.5>
    </PID.3>
</PID.3.LST>

I want to load only the first CX.1 value which CX.5 value contains 'TN'.

This is the XSLT code that I'm using, but it returns all CX.1 values.

<xsl:variable name="UR" select="CX.5"/>
<xsl:if test="substring($UR,1,2)='TN'">
    My ID:  <xsl:variable name="URsub" select="substring-after('TN',$UR)"/>
    <xsl:value-of select="CX.1"/>                                       
</xsl:if>

In another word, I need to break my for-each in XSLT

I need to fetch only first CX.1 value which CX.5 value starts with 'TN'

The matching expressing you are looking for is

//CX.1[starts-with(../CX.5,'TN')][1]

In a whole template this looks like this:

<xsl:template match="/">
  <xsl:value-of select="//CX.1[starts-with(../CX.5,'TN')][1]" />
</xsl:template>

这个XPath将选择第一个CX.1元素,它的兄弟CX.5元素包含“TN”:

(/PID.3.LST/PID.3[contains(CX.5,"TN")]/CX.1)[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM