如何在XQuery中获取多结果:按性别统计社交媒体外貌评论
Great question! Let's adjust your code to count male commenters' appearance-related comments, plus get a combined total for both genders. First, let's fix a tiny syntax typo in your original female count query (you missed a closing quote on the @gender attribute):
-- Corrected count for female commenters count(doc("women.xml")/thread/comment[@gender="female"]/appearance)
Now here's how to expand this to cover all your needs:
1. Count Appearance Comments from Male Commenters
This is straightforward—just swap the @gender value to "male":
count(doc("women.xml")/thread/comment[@gender="male"]/appearance)
2. Get All Counts in One Efficient Query
Instead of loading the XML document multiple times (which is inefficient), you can run a single query that calculates all three values at once and returns a structured result:
let $social_media_data := doc("women.xml") let $female_appearance_comments := count($social_media_data/thread/comment[@gender="female"]/appearance) let $male_appearance_comments := count($social_media_data/thread/comment[@gender="male"]/appearance) let $total_appearance_comments := $female_appearance_comments + $male_appearance_comments return <appearance_comment_summary> <female_commenters>{$female_appearance_comments}</female_commenters> <male_commenters>{$male_appearance_comments}</male_commenters> <total_all_genders>{$total_appearance_comments}</total_all_genders> </appearance_comment_summary>
What This Does
- We first store the entire XML document in a variable (
$social_media_data) so we only parse it once. - For each gender, we filter comments by the
@genderattribute and count how many have anappearancechild element. - The total count is simply the sum of the male and female counts.
- The final result is a clean XML structure that makes it easy to read or use the counts in other processes.
内容的提问来源于stack exchange,提问作者J Brooks
相关产品推荐
相关产品推荐

