Łukasz Gruner
Łukasz Gruner

Reputation: 3229

xslt, how to select tags, based on the contents of another same level tag

My source file looks like this:

<stuff> 
<s>
    <contents>
      <code>503886</code>
      <code>602806</code>
    </contents>
    ...
</s>
<p>
    <code>344196</code>
    <export>true</export>
    ...
</p>
<!-- more 's' and 'p' tags -->
...
</stuff>

I need to iterate over 's' and choose those - which inside 'contents' tag have a 'code' that belongs to a 'p' that has export=true.

I've been trying to solve this for the last couple of hours. Please share some ideas.

Upvotes: 1

Views: 302

Answers (2)

user357812
user357812

Reputation:

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="kSByCode" match="s" use="contents/code"/>
    <xsl:template match="text()"/>
    <xsl:template match="p[export='true']">
        <xsl:copy-of select="key('kSByCode',code)"/>
    </xsl:template>
</xsl:stylesheet>

With this input:

<stuff>
    <s>
        <contents>
            <code>503886</code>
            <code>602806</code>
        </contents>
    </s>
    <p>
        <code>602806</code>
        <export>true</export>
    </p>
</stuff>

Output:

<s>
    <contents>
        <code>503886</code>
        <code>602806</code>
    </contents>
</s>

Note: Whenever there are cross references, use keys.

Edit: Missed iterate over s part. Thanks, Dimitre!

Edit 2: Re reading this answer I saw that it might be confusing. So, for a expression selecting the nodes, use:

key('kSByCode',/stuff/p[export='true']/code)

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

I need to iterate over 's' and choose those - which inside 'contents' tag have a 'code' that belongs to a 'p' that has export=true.

Use:

<xsl:apply-templates select=
 "/*/s
      [code
      =
       /*/p
          [export='true']
                      /code]"/>

Upvotes: 0

Related Questions