xml - Selecting the sibling or niece of the loop varaible in "for" loop in XQuery -
suppose there xml file:
<adam> <jacksons> <s1>jack</s1> <s2>sara</s2> </jacksons> <petersons> <s1>peter</s1> <n> <s2>anna</s2> </n> </petersons> <davidsons> <q> <s1>david</s1> </q> <n> <s2>suzann</s2> </n> </davidsons> </adam> i s2 sibling or niece of each s1 call function on both of them inside loop, please note don't know structure of xml except each s1 , s2 have common ancestor, tried
let $db := doc('test2.xq') $s1 in $db//s1 let $s2 := $db//*[//$s1]/(s2, */s2) return <p> {$s1/text()} marry {$s2/text()} </p> it returns
<p>jack marry saraannasuzann</p> <p>peter marry saraannasuzann</p> <p>david marry saraannasuzann</p> i expect
<p>jack marry sara</p> <p>peter marry anna</p> <p>david marry suzann</p>
the problem query search whole document s2 nodes again, not same item.
don't search s1 elements, pairs , print message each of them.
for $pair in //item return <p>{ $pair//s1/text() } marry { $pair//s2/text() }</p> you could s1 elements , find matching s2 nodes, harder read , understand, , pobably performs worse because of descending down tree find item both belong to:
for $s1 in //s1 let $s2 := $s1//ancestor::item//s2 return <p>{ $s1/text() } marry { $s2/text() }</p> in both cases, depending on what's allowed in document might want add safeguards find pairs of two. restrictive example be
for $pair in //item let $s1 := $pair//s1, $s2 := $pair//s2 count($s1) = 1 , count($s2) = 1 return <p>{ $s1/text() } marry { $s2/text() }</p> for completeness, possible without explicit loop (while not being reasonable solution, harder read , understand if growing in complexity):
//item/element p { concat(.//s1/text(), " marry ", .//s2/text()) }
Comments
Post a Comment