使用带sum条件的XPath在C#中筛选TV-show节点问题求助
Fixing XPath Query to Find TV Shows with Total Episodes Over a Threshold
Your current XPath expression isn't calculating the total episodes correctly—let's fix that. The issue is that sum(seasons) doesn't sum up the episode counts inside each season; instead, it tries to sum the <seasons> node itself (which evaluates to 0 in XPath, since it's not a numeric value).
Corrected Code
Here's the updated function with the proper XPath to sum all <episodes> values under each <season>:
public XmlNodeList Query7(XmlDocument xmlDoc, int amountOfEpisodes) { // XPath now targets each season's episodes and sums their values string xpath = $"Netflix/TV-shows/TV-show[sum(seasons/season/episodes) > {amountOfEpisodes}]"; XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath); return xmlNodeList; }
Why This Works
- The XPath
sum(seasons/season/episodes)traverses from each<TV-show>down to every<episodes>node inside its<season>children, then sums all those numeric values. - For your sample XML:
- Game of Thrones has a total of
10+10+10+10+10+10+7 = 67episodes - The Sopranos has
13+13+13+13+13+21 = 86episodes
- Game of Thrones has a total of
- When you pass
70as the threshold, only The Sopranos will be returned, which matches your expected result.
Notes
- You don't need to use
>in the C# string—directly using>works fine here, since we're not building XML markup, just an XPath expression. - If there's a chance your
<episodes>nodes might contain non-numeric values, you can addnumber()to ensure safe conversion:sum(seasons/season/number(episodes))
内容的提问来源于stack exchange,提问作者Kumar Aldani
相关产品推荐
相关产品推荐

