0
votes

I have the following XML document (This example is from W3schools.com with modifications):

<bookstore>
    <book>
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <section>Children</section>
      <section>Recent</section>
      <year>2005</year>
      <price>30.00</price>
    </book>

    <book>
      <title lang="en">Harry Potter</title>
      <author>J K. Rowling</author>
      <section>Children</section>
      <section>Recent</section>
      <year>2005</year>
      <price>29.99</price>
    </book>

    <book>
      <title lang="en">Learning XML 2: The Reckoning</title>
      <author>Erik T. Simpson</author>
      <section>Terror</section>
      <year>2003</year>
      <price>9.95</price>
    </book>

</bookstore>

How can I retrieve the books which SECTION is the ONLY ONE in the entire document and there is no duplicate? I tried the following XQuery (I need an XQuery for this):

for $x in doc("books.xml")/bookstore/book/
where distinct-values($x/section)
return $x

But it seems returns all of them without duplicates and I want to retrieve the last node, because is the only one with that section.

Any idea? Thank you very much for your support and help!

1
Are you looking for all book elements with only one section child element? What happens if there is a book with several section child element which are all unique across the document, do you want to select it? Also which version of XQuery do you use?Martin Honnen
You've given sample data (good), but you've omitted the desired result of your query (bad). Please clarify what you are trying to achieve - answering Martin's question should help with this.Joe Wicentowski
Thanks for the advise, I'll be more specific next time. Fortunately, Martin answered me in a fantastic way. Thank you again!Joanmacat

1 Answers

2
votes

If you select /bookstore/book[not(section = (preceding-sibling::book/section | following-sibling::book/section))] then you select all book elements which do not have a section equal to any section of other book elements.