Chloraphil
Chloraphil

Reputation: 2849

Select XML nodes based on matching values in other nodes

Given the following xml

<dsQueryResponse>
<Proposals>
    <Rows>
        <Row ID="1"/>
        <Row ID="2"/>
        <Row ID="3"/>
    </Rows>
</Proposals>
<ProposalReviewers>
    <Rows>
        <Row ID="1" ProposalID="1"/>
        <Row ID="2" ProposalID="1"/>
        <Row ID="3" ProposalID="2"/>
    </Rows>
   </ProposalReviewers>
</dsQueryResponse>

What xpath expression, or XSLT transform (Xslt 1.0), will give me the following output, based on the values of attribute ProposalID?

<Rows>
    <Row ID="1"/>
    <Row ID="2"/>
</Rows>

I know if I'm running inside of a for-each I can use current(), but I am hoping to do this outside the for-each.

Upvotes: 0

Views: 50

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

Your question can be read in many ways, and I am mostly guessing here. Still, the only logical way to return only the two Rows from the input that has three (or six), seems to be this:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="proposal" match="Proposals/Rows/Row" use="@ID" />

<xsl:template match="/dsQueryResponse">
    <Rows>
        <xsl:copy-of select="key('proposal', ProposalReviewers/Rows/Row/@ProposalID)"/>
    </Rows>
</xsl:template>

</xsl:stylesheet>

To understand how this works, see: https://www.w3.org/TR/xslt/#key

Upvotes: 1

Related Questions