ffffff01
ffffff01

Reputation: 5238

Select all elements that does not exist in another node with XSLT

I want to select all elements that does not exist in another node.

<root>
  <users>
    <array>
      <name>John</name>
      <age>30</age>
    </array>
    <array>
      <name>Joe</name>
      <age>30</age>
    </array>
    <array>
      <name>Lou</name>
      <age>30</age>
    </array>
  </users>
  <selected_users>
    <name>Joe</name>
    <age>30</age>
  </selected_users>
</root>

So what I want from this list is John and Lou since their not listed under the selected users node..

Upvotes: 1

Views: 2505

Answers (2)

Daniel Haley
Daniel Haley

Reputation: 52848

You can use this xpath:

/*/users/array/name[not(.=/*/selected_users/name)]

to get "John" and "Lou". I can add an XSLT example if you specify what kind of output you're trying to get.

Upvotes: 2

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

Here is a short and simple way to do this:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" method="text"/>

    <xsl:template match="users/array/name[not(.=/*/selected_users/name)]">
        <xsl:value-of select="concat(., ' ')"/>
    </xsl:template>
    <xsl:template match="text()"/>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<root>
    <users>
        <array>
            <name>John</name>
            <age>30</age>
        </array>
        <array>
            <name>Joe</name>
            <age>30</age>
        </array>
        <array>
            <name>Lou</name>
            <age>30</age>
        </array>
    </users>
    <selected_users>
        <name>Joe</name>
        <age>30</age>
    </selected_users>
</root>

the wanted, correct result is produced:

John Lou 

Note:

If you want to get the wanted name elements in a variable, use:

    <xsl:variable name="vSomeName" select=
"/*/users/array/name[not(.=/*/selected_users/name)]"/>

Upvotes: 4

Related Questions