0

I have a requirement here, I would try to keep it in very simple terms,

I have a raw information in the form of XML:

<MyFruits> <Apple>23</Apple> <Mango>12</Mango> <Orange>10</Orange> <Apple>19</Apple> </MyFruits>

I want to get only unique fruits among them. (Apple,Mango and Orange)

Can anyone write an XPath to retrieve this? Status : Not Answered

You can give your answers as comments

Hint : Had the XML be like below

<MyFruits> <Apple>23</Apple> <Apple>19</Apple> <Mango>12</Mango> <Orange>10</Orange> </MyFruits>

This XPath would have worked

//MyFruits/[not(name(.)=name(following-sibling::))]

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
HookUp
  • 393
  • 1
  • 6
  • 20

1 Answers1

0

Check if a preceding sibling has the same name, not a following sibling. That way the first encounter will be output and not any following ones.

/MyFruits/name(.)[not(name(.)=name(preceding-sibling::*)]

Paul
  • 4,009
  • 1
  • 17
  • 15
  • Won't work - `name(preceding-sibling::*)` gives you the name of one particular node (the context node's preceding sibling that is first in document order), it doesn't provide a way to compare against each preceding sibling in turn. – Ian Roberts Jul 16 '14 at 12:30
  • `preceding-sibling::*` will give you all preceding siblings, where as `preceding-sibling::*[1]` will give you the first preceding sibling. – Paul Jul 16 '14 at 12:32
  • 2
    yes, `preceding-sibling::*` will give you a node set containing all the preceding sibling elements. If you apply the `name` function to such a node set then XPath 1.0 will give you the name of the first node in the set in document order and ignore the other nodes, and XPath 2.0 will give you a type error if the set contains more than one node. – Ian Roberts Jul 16 '14 at 14:14