Well, here is one way (this uses the Shakespeare database):

 

fn:count(cts:search(//SPEECH, 

              cts:element-value-query(xs:QName("SPEAKER"),
"HAMLET"))/LINE)

 

Hamlet has 1495 lines.

 

or if you want them all:

 

<ALL>{

for $x in fn:distinct-values(//SPEAKER/text())

return

<SPEAKER>

  <Name>{$x}</Name>

  <NumberOfLines>{fn:count(cts:search(//SPEECH, 

 
cts:element-value-query(xs:QName("SPEAKER"),$x))/LINE)}</NumberOfLines>

</SPEAKER>

}</ALL>

 

and if you create an element range index on SPEAKER, you can use a
lexicon to get the distinct speakers:

 

<ALL>{

for $x in cts:element-values(xs:QName("SPEAKER"))

return

<SPEAKER>

  <Name>{$x}</Name>

  <NumberOfLines>{fn:count(cts:search(//SPEECH, 

 
cts:element-value-query(xs:QName("SPEAKER"),$x))/LINE)}</NumberOfLines>

</SPEAKER>

}</ALL>

 

-Danny

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Eric
Caplain
Sent: Thursday, March 13, 2008 7:54 PM
To: [email protected]
Subject: [MarkLogic Dev General] how to implement an accumulator

 

I've some XML like:

<speech>
   <speaker>Joe</speaker>
   <line>blah blah blah</line>
   ...
   <line>this that and the other thing</line>
</speech>

I can get each speaker and then get each speech of that speaker and a
count of lines in each speech, but I haven't been able to get the total
count of all lines by a speaker.

In the following, the function line-count returns the count of lines in
each speech, but I need to accumulate these counts and return that, and
I haven't been able to figure out a way to do that. Any suggestions
would be appreciated.

define function line-count($s as xs:string) as xs:integer {
   let $count := 0
   for $_speech in doc("speeches.xml")//speech
   where some $_speaker in $_speech/speeker
   satisfies ($_speaker/text() = $s)
   return count($_speech/line)    
}

<speakers>
{
  let $speech := doc("speeches.xml")//speech
  for $speaker in distinct-values($speech/speaker)
  order by $speaker
  return
     <speaker>
        <name>{$speaker}</name>
        <count>{ line-count($speaker) }</count>
     </speaker>
}
</speakers>

_______________________________________________
General mailing list
[email protected]
http://xqzone.com/mailman/listinfo/general

Reply via email to