1

I have "Library.xml" file containing book records as

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>DBMS</title>
        <author>Korth</author>
        <publisher>Pragati</publisher>
        <price>500</price>
    </book>

    <book>
        <title>C Programming</title>
        <author>Balguruswami</author>
        <publisher>Vision</publisher>
        <price>1250</price>
    </book>

    <book>
        <title>DBMS</title>
        <author>Balguruswami</author>
        <publisher>Vision</publisher>
        <price>1300</price>
    </book>

    <book>
        <title>DBMS</title>
        <author>Ramakrishna</author>
        <publisher>Nirali</publisher>
        <price>350</price>
    </book>

    <book>
        <title>C++</title>
        <author>E Balguruswami</author>
        <publisher>Techmax</publisher>
        <price>350</price>
    </book>

</library>

How do I get count of books of DBMS only using XQuery - FLOWER ? I've tried this:

let $books := (doc("LibraryXML.xml")/library/book)

    return <result>
    {
        for $x in $books
        where $x/title = "DBMS"
        return count($x)
    }
    </result>

And according the library.xml the answer should be 3. But I'm getting it as:

<?xml version="1.0" encoding="UTF-8"?>
<result>1 1 1</result>
  • You're probably coming from a SQL background, where every query is a SELECT, and therefore assuming that in XQuery every query is a FLWOR. But FLWOR is needed only for the most complex queries. Most simple queries can be done with a simple XPath expression such as`count(//title)`. – Michael Kay Apr 08 '20 at 16:50

1 Answers1

2

To do it in XQuery 3.0 there is no need in a full FLWOR expression with all clauses.

Check it out.

XQuery

let $library := doc("e:\Temp\LibraryXML.xml")/library/book[title='DBMS']
return <result>{count($library)}</result>

Output

<result>3</result>
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • 1
    And even more simple, do it in one-line statement without letting a variable: `{count(doc("e:\Temp\LibraryXML.xml")/library/book[title='DBMS'])}` – Mads Hansen Apr 08 '20 at 17:14
  • 1
    Good to hear that the proposed solution is working for you. Please don't forget to mark it as Answer – Yitzhak Khabinsky Apr 17 '20 at 00:28