Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinct in Xpath?

I have this XML file, from which I'd like to count the number of users referenced in it. But they can appear in more than one category, and I'd like these duplicates not to be taken into account.
In the example below, the query should return 3 and not 4. Is there a way in XPath to do so? Users are not sorted at all.

<list>
  <group name='QA'>
    <user name='name1'>name1@email</user>
    <user name='name2'>name2@email</user>
  </group>
  <group name='DEV'>
    <user name='name3'>name3@email</user>
    <user name='name2'>name2@email</user>
  </group>
</list>
like image 361
Antoine Avatar asked May 11 '10 15:05

Antoine


People also ask

How to use distinct values in XPath?

distinct-values() is available in XPath 2.0. Are you using that? If distinct-values() is not available, the standard way of getting distinct values is to use not(@result = preceding:: @result) to get unique @result. It will give you the first occurrence only.

Is XPath unique?

Unlike ID attributes, every element in a web page has a unique XPath. An XPath (XML Path Language) is a query language for selecting nodes from XML like documents, such as HTML in our case.


2 Answers

A pure XPath 1.0 -- one-liner:

Use:

count(/*/group/user[not(. = ../following-sibling::group/user)])

like image 91
Dimitre Novatchev Avatar answered Oct 10 '22 03:10

Dimitre Novatchev


using the functions namespace http://www.w3.org/2005/xpath-functions you can use

distinct-values(//list/group/user)

UPDATE:

At the top of your xsl/xslt file you should have a stylesheet element, map the url above to the prefix fn as below...

<xsl:stylesheet version="1.0"
 xmlns:fn="http://www.w3.org/2005/xpath-functions"
 >

then you can use

select="fn:distinct-values(//list/group/user)"

this would assume you are doing this in templates and not in some xpathdocument object inwhich case you need to use a namespacemanager class.

links...

XSLT: Add namespace to root element

http://www.xqueryfunctions.com/xq/fn_distinct-values.html

http://msdn.microsoft.com/en-us/library/d6730bwt(VS.80).aspx

Otherwise try Dimitre Novatchev's answer.

like image 43
gingerbreadboy Avatar answered Oct 10 '22 03:10

gingerbreadboy