基于XQuery 1.0统计无界结构元素中指定值的出现次数
<OutcomeCode> Elements Got it, let's tackle this XQuery problem step by step. You need to count how many times the value FC appears in the <OutcomeCode> elements, working with the unbounded <DataDetail> and <PerEquipment> structures in your XML.
First, let's recap your input XML structure (fixed the closing tag typo from <DataDetailsResponse> to <DataDetails> for validity):
<v4:DataDetails xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v4="http://services.xx.net/PP/v4"> <v4:DataDetail> <v4:PerEquipment> <v4:OutcomeCode>FC</v4:OutcomeCode> <v4:OutcomeDescription>FC Data</v4:OutcomeDescription> </v4:PerEquipment> <v4:PerEquipment> <v4:OutcomeCode>FC</v4:OutcomeCode> <v4:OutcomeDescription>FC Data</v4:OutcomeDescription> </v4:PerEquipment> </v4:DataDetail> <v4:DataDetail> <v4:PerEquipment> <v4:OutcomeCode>OG</v4:OutcomeCode> <v4:OutcomeDescription>OG Data</v4:OutcomeDescription> </v4:PerEquipment> <v4:PerEquipment> <v4:OutcomeCode>FC</v4:OutcomeCode> <v4:OutcomeDescription>FC Data</v4:OutcomeDescription> </v4:PerEquipment> </v4:DataDetail> </v4:DataDetails>
Solution XQuery Code
Here's a concise XQuery 1.0 query that will return the expected count of 3:
declare namespace v4 = "http://services.xx.net/PP/v4"; count(/v4:DataDetails/v4:DataDetail/v4:PerEquipment/v4:OutcomeCode[text() = 'FC'])
How It Works
- Namespace Declaration: First, we declare the
v4namespace to match the one in your XML—this is crucial because XQuery requires explicit namespace handling for elements with prefixes. - Targeted XPath Path: The path
/v4:DataDetails/v4:DataDetail/v4:PerEquipment/v4:OutcomeCodenavigates directly through the unbounded structures to reach all<OutcomeCode>elements. Using the full path instead of//ensures we only count elements in the exact hierarchy you care about (avoids accidental matches elsewhere if the XML had other<OutcomeCode>elements). - Filter & Count: The predicate
[text() = 'FC']filters the<OutcomeCode>elements to only those with the value "FC", andcount()returns the total number of matching elements.
If you prefer a more flexible approach (for example, if the hierarchy might vary slightly), you could use the shorthand path //v4:OutcomeCode[text() = 'FC'] inside the count() function—this will find all <OutcomeCode> elements with value "FC" anywhere in the XML, which also works for your input.
Expected Result
Running this query on your input XML will return:
3
内容的提问来源于stack exchange,提问作者kumarb

