简体   繁体   中英

XQuery - using GROUP BY with WHERE condition to retrieve XML file names

I am having trouble creating an XQuery 3.0 (using BaseX 9.7) to retrieve names of XML files in a collection which satisfies certain conditions: Having more than 1 occurrence of the same 'type' element if another element ('author') has a certain value.

Simplified XML examples:

"good.xml":

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <!-- OK -->
    <books>
        <book>
            <author>Alice</author>
            <type>mystery</type>
        </book>
        <book>
            <author>Alice</author>
            <type>fantasy</type>
        </book>
    </books>

"not_good.xml":

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- NOT OK -->
<books>
    <book>
        <author>Alice</author>
        <type>horror</type>
    </book>
    <book>
        <author>Alice</author>
        <type>horror</type>
    </book>
</books>

If the number of possible 'type' are small, I can use the following XQuery:

for $books in collection('group_test')/books[
       count(.//book[author = 'Alice'][type = 'mystery']) > 1
    or count(.//book[author = 'Alice'][type = 'fantasy']) > 1
    or count(.//book[author = 'Alice'][type = 'horror']) > 1
]
return db:path($books)

I have tried the following XQuery, but it does not find anything:

for $books in collection('group_test')/books[/book/author = 'Alice']
group by $type := //book/type 
where count($type) > 1

return db:path($books)

Perhaps

for $book in collection('group_test')/books/book[author = 'Alice']
group by $type := $book/type 
where count($book) > 1

return ($book!db:path(.))

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