Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I use XPath to select distinct elements based on multiple child elements?
    primarykey
    data
    text
    <p>I need to use XPath to select distinct elements based on multiple child elements.</p> <p>I have some XML like this:</p> <pre><code>&lt;Cars&gt; &lt;Car&gt; &lt;Make&gt;SuperCar&lt;/Make&gt; &lt;Year&gt;2009&lt;/Year&gt; &lt;/Car&gt; &lt;Car&gt; &lt;Make&gt;SuperCar&lt;/Make&gt; &lt;Year&gt;2010&lt;/Year&gt; &lt;/Car&gt; &lt;Car&gt; &lt;Make&gt;AwesomeCar&lt;/Make&gt; &lt;Year&gt;2010&lt;/Year&gt; &lt;/Car&gt; &lt;Car&gt; &lt;Make&gt;SuperCar&lt;/Make&gt; &lt;Year&gt;2009&lt;/Year&gt; &lt;/Car&gt; &lt;/Cars&gt; </code></pre> <p>And I need to use XPath (I'm limited to XPath 1.0) to select only distinct elements, where distinct is defined by both <code>Make</code> and <code>Year</code>. </p> <p>In the example above this would mean returning all of the <code>Car</code> objects except the last one (as this is a duplicate of the first <code>Car</code>).</p> <p>In a typical situation (i.e. where objects were identified by a single key field) I would use an XPath similar to this:</p> <pre><code>/*/Car[not(./Id/text()=following-sibling::Car/Id/text())] </code></pre> <p>However, I can't quite work out how to adapt this to correctly use multiple fields.</p> <p>I considered something like this:</p> <pre><code>/*/Car[not(./Make/text()=following-sibling::Car/Make/text() and ./Model/text()=following-sibling::Car/Model/text())] </code></pre> <p>But that checks if the <code>Make</code> is used anywhere and if the <code>Model</code> is used anywhere, without ensuring that they are necessarily used on the same <code>Car</code>. For example it incorrectly excludes the first <code>Car</code> from the following sample XML:</p> <pre><code>&lt;Cars&gt; &lt;Car&gt; &lt;Make&gt;SuperCar&lt;/Make&gt; &lt;Year&gt;2009&lt;/Year&gt; &lt;/Car&gt; &lt;Car&gt; &lt;Make&gt;SuperCar&lt;/Make&gt; &lt;Year&gt;2010&lt;/Year&gt; &lt;/Car&gt; &lt;Car&gt; &lt;Make&gt;AwesomeCar&lt;/Make&gt; &lt;Year&gt;2009&lt;/Year&gt; &lt;/Car&gt; &lt;/Cars&gt; </code></pre> <p>Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload