woodpecker
woodpecker

Reputation: 11

XPath Select a value from a cousin node

I have the following xml

<FreightLabelData>
  <Consignments>
    <Consignment>
      <References>
        <Reference>
          <ReferenceNumber>RefLine1</ReferenceNumber>
          <SequenceNumber>1</SequenceNumber>
        </Reference>
        <Reference>
          <ReferenceNumber>RefLine2</ReferenceNumber>
          <SequenceNumber>2</SequenceNumber>
        </Reference>
      </References>
      <FreightLabels>
        <FreightLabel>
          <ReferenceSequenceNumber>1</ReferenceSequenceNumber>
        </FreightLabel>
        <FreightLabel>
          <ReferenceSequenceNumber>2</ReferenceSequenceNumber>
        </FreightLabel>
      </FreightLabels>
    </Consignment>
  </Consignments>
</FreightLabelData>

My xslt has a for loop that is initiated as

<xsl:for-each select="/FreightLabelData/Consignments/Consignment/FreightLabels/*">

For each FreightLabel I need to find the related cousin Reference/ReferenceNumber where FreightLabel/ReferenceSequenceNumber = Reference/SequenceNumber

I've spent quite a bit of time looking for the answer without any luck. Does anyone know how to do this?

Thanks

Upvotes: 1

Views: 168

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

In XSLT, you could use:

/FreightLabelData/Consignments/Consignment/References/Reference[SequenceNumber=current()/ReferenceSequenceNumber]

However, it would be better to use XSLT's dedicated mechanism for handling cross-references. Start by defining a key at the top level of your stylesheet:

<xsl:key name="ref" match="Reference" use="SequenceNumber" />

Then, from the context of FreightLabel, you can select the corresponding Reference using the following expression:

key('ref', ReferenceSequenceNumber)

See: http://www.w3.org/TR/xslt/#key

Upvotes: 1

Related Questions