简体   繁体   中英

XPath to select distinct values from XML file

I have the following XML file

<people>
<person>
    <name>Diana B. Aust</name>
    <address>8325 Meadow Rd</address>
    <city>Dallas, TX</city>
</person>
<person>
    <name>Diana C. Aust</name>
    <address>8325 Meadow Rd</address>
    <city>Dallas, TX</city>
</person>
<person>
    <name>Acelia T. Peguero</name>
    <address>59 Terry Ave</address>
    <city>Amityville, NY</city>
</person>
<person>
    <name>Acelia U. Peguero</name>
    <address>58 Terry Ave</address>
    <city>Amityville, NY</city>
</person>
</people>

I want to select all persons based on unique address + city combo. How would I do this with an XPath query? The correct query should return nodes #1,#3 and #4.

XPath 2.0 solution:

/*/person[not(concat(city, address)=preceding-sibling::*/concat(city, address))]

An XSLT 1.0 Muenchian Method solution (for reference only):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:key name="byAddressAndCity" match="person" 
             use="concat(address, '|', city)"/>
    <xsl:template match="/">
        <xsl:copy-of
            select="*/person[generate-id()=generate-id(
                key('byAddressAndCity', concat(address, '|', city))[1])]"/>
    </xsl:template>
</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM