Conor
Conor

Reputation: 107

XSLT counter in xpath

I need to populate an XML attribute "code" with the value from Container/Patient/Races/Race[number]/Code. I can't get the attribute to populate with a value. See XML and XSLT below.

I've tried various scenarios testing with https://www.freeformatter.com/xsl-transformer.html

    <?xml version="1.0" encoding="UTF-8"?>
    <Container>
      <Patient>
        <Races>
          <Race>
            <Code>2106-3</Code>
          </Race>
          <Race>
            <Code>2106-9</Code>
          </Race>
        </Races>
     </Patient>
    </Container>


    <?xml version="1.0" encoding="UTF-8"?>
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sdtc="urn:hl7-org:sdtc">
      <xsl:template match="/">
        <raceCode code="{Container/Patient/Races/Race[1]/Code}" />
          <xsl:for-each select="Container/Patient/Races/Race[position()>1]">
          <xsl:variable name="pos" select="position()"/>
          <sdtc:raceCode code="{Container/Patient/Races/Race[$pos]/Code}" />
      </xsl:for-each>
      </xsl:template>
    </xsl:stylesheet>

This is what outputs:

     <raceCode xmlns:sdtc="urn:hl7-org:sdtc" code="2106-3"/>
     <sdtc:raceCode xmlns:sdtc="urn:hl7-org:sdtc" code=""/>

but I want the following:

    <raceCode xmlns:sdtc="urn:hl7-org:sdtc" code="2106-3"/>
    <sdtc:raceCode xmlns:sdtc="urn:hl7-org:sdtc" code="2106-9"/>

Upvotes: 0

Views: 86

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

When you do:

 <xsl:for-each select="Container/Patient/Races/Race[position()>1]">

you are put in the context of Race. From this context, the expression:

Container/Patient/Races/Race[$pos]/Code

selects nothing. You would get a different result if you changed:

<sdtc:raceCode code="{Container/Patient/Races/Race[$pos]/Code}" />

to use an absolute path:

<sdtc:raceCode code="{/Container/Patient/Races/Race[position()>1][$pos]/Code}" />

but in fact you can do simply:

<sdtc:raceCode code="{Code}" />

and dispose of the variable.

Upvotes: 1

Related Questions