user3421997
user3421997

Reputation: 53

Selecting only distinct values using XPath 1.0

How would I return only the unique City value where the Name of the state = 'Washington' using XPath 1.0?

<StateDataSet>
    <State>
        <Name>Washington</Name>
        <City>Seattle</City>
        <business>Starbucks</business>
    </State>
    <State>
        <Name>Washington</Name>
        <City>Seattle</City>
        <business>Amazon</business>
    </State>
    <State>
        <Name>Washington</Name>
        <City>Redmond</City>
        <business>Microsoft</business>
    </State>
    <State>
        <Name>Washington</Name>
        <City>Redmond</City>
        <business>Starbucks</business>
    </State>
    <State>
        <Name>Washington</Name>
        <City>Seattle</City>
        <business>Dicks</business>
    </State>
    <State>
        <Name>Alaska</Name>
        <City>Anchorage</City>
        <business>Starbucks</business>
    </State>
    <State>
        <Name>Oregon</Name>
        <City>Portland</City>
        <business>Starbucks</business>
    </State>
    <State>
        <Name>Alaska</Name>
        <City>Gnome</City>
        <business>Starbucks</business>
    </State>
</StateDataSet>

So far I've tried the following XPath query:

/StateDataSet/State[Name ='Washington' and not (State[Name='Washington'] = following-sibling::State[Name='Washington'])]/City

This returned the city in Washington but the values are not unique. I tested my query using xpathtester.com

What am I doing wrong? I'm basing my query on get-distinct-values-within-specific-attributes

Upvotes: 2

Views: 350

Answers (1)

kjhughes
kjhughes

Reputation: 111541

This XPath,

/StateDataSet/State[Name ='Washington' and 
                    not(City = preceding-sibling::State[Name='Washington']/City)]
             /City

will select the unique City elements in State elements with Name = 'Washington':

<City>Seattle</City>
<City>Redmond</City>

as requested.

Upvotes: 2

Related Questions