source: TI07-MOLES/tags/wsgi-beta/ndg_xqueries.py @ 2583

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/tags/wsgi-beta/ndg_xqueries.py@5134
Revision 2583, 96.1 KB checked in by ko23, 12 years ago (diff)

New version of ndg_xqueries.py and examples of new StubBs?

Line 
1# This version using xqueries from rev 1914 of
2# TI07-MOLES/trunk/JavaCode/returnmolesxmldb/ndg/services/returnmoles/Main.java
3# Update DIF/DC queries
4listingQuery='''
5declare default element namespace 'http://ndg.nerc.ac.uk/moles';for $DE
6in
7collection('TargetCollection')/dgMetadata/dgMetadataRecord[exists(dgDataEntity)] return
8<dgMetadataRecord>{$DE/dgMetadataID/repositoryIdentifier}
9{$DE/dgMetadataID/localIdentifier}<fileName>{util:document-name($DE)}</fileName></dgMetadataRecord>
10'''
11
12ObjectTypeQuery = '''declare default element namespace 'http://ndg.nerc.ac.uk/moles';declare variable $targetCollection as xs:string {'TargetCollection'};for $Obj in collection($targetCollection)/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier='RepositoryID' and dgMetadataID/localIdentifier='LocalID']  return <objectType>{if (exists($Obj/dgDataEntity)) then 4 else (if (exists($Obj/dgObservationStation)) then 3 else (if (exists($Obj/dgDataProductionTool)) then 2 else (if (exists($Obj/dgActivity)) then 1 else (0))))}</objectType>'''
13
14StubBDEQuery = '''
15declare default element namespace 'http://ndg.nerc.ac.uk/moles/dataentity';
16declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
17declare namespace moles='http://ndg.nerc.ac.uk/moles';
18
19import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
20import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
21(:
22Will return when scope problem sussed... ;(
23import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
24:)
25declare variable $targetCollection as xs:string {'TargetCollection'};
26declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
27declare variable $localIdentifier as xs:string {'LocalID'};
28(: replacable parameters
29declare variable $targetCollection as xs:string {'/db/ndg_B_metadata'};
30declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
31declare variable $localIdentifier as xs:string {'dataent_chablis'};
32:)
33
34declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
35(: Returns a 'stubB' style activity record to expand an activity record :)
36(: Security not implemented here yet :)
37{
38let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
39moles:dgMetadataID/moles:localIdentifier=$locid
40and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
41return
42element  {$out-element-name} {
43($SRAct/moles:dgMetadataID),
44($SRAct/moles:dgMetadataDescription),
45($SRAct/moles:name),
46($SRAct/moles:abbreviation),
47($SRAct/moles:logos)
48} (: </activity> :)
49} ;
50
51declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
52(: Returns a 'stubB' style observation station record to expand an data entity record :)
53(: Security not implemented yet :)
54{
55let $SRDE := $DE
56return 
57element {$out-element-name} {
58($SRDE/moles:dgMetadataID),
59($SRDE/moles:dgMetadataDescription),
60($SRDE/moles:name),
61($SRDE/moles:abbreviation)
62} (: </dgDataEntity> :)       
63} ;
64
65declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
66(: Returns a 'stubB' style dpt record to expand a dpt record :)
67(: Security not implemented yet :)
68{
69let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
70moles:dgMetadataID/moles:localIdentifier=$locid
71and
72moles:dgMetadataID/moles:repositoryIdentifier=$repid
73]
74return 
75element {$out-element-name} {
76$SRDPT/moles:dgMetadataID,
77$SRDPT/moles:dgMetadataDescription,
78$SRDPT/moles:name,
79$SRDPT/moles:abbreviation,
80$SRDPT/moles:logos
81} (: </dataproductiontool> :)
82} ;
83
84declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
85(: Returns a 'stubB' style observation station record to expand an observation station record :)
86(: Security not implemented here yet;  :)
87{
88let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
89moles:dgMetadataID/moles:localIdentifier=$locid
90and
91moles:dgMetadataID/moles:repositoryIdentifier=$repid
92]
93return
94element {$out-element-name} {
95($SRObsStn/moles:dgMetadataID),
96($SRObsStn/moles:dgMetadataDescription),
97($SRObsStn/moles:name),
98($SRObsStn/moles:abbreviation),
99($SRObsStn/moles:logos)
100}
101} ;
102
103declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
104(: Returns a 'stubB' style observation station record to expand a person record :)
105(: Security not implemented yet :)
106{
107let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
108moles:dgMetadataID/moles:localIdentifier=$locid
109and
110moles:dgMetadataID/moles:repositoryIdentifier=$repid
111]
112return
113element  {$out-element-name}
114{
115($person/moles:name),
116($person/moles:contactDetails),
117($person/moles:dgMetadataID)
118}
119} ;
120
121declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
122(: Returns a 'stubB' style observation station record to expand an organisation record :)
123(: Security not implemented yet :)
124{
125let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
126moles:dgMetadataID/moles:localIdentifier=$locid
127and
128moles:dgMetadataID/moles:repositoryIdentifier=$repid
129]
130return
131element  {$out-element-name} {
132$org/moles:dgMetadataID,
133$org/moles:name,
134$org/moles:abbreviation,
135$org/moles:contactDetails,
136$org/moles:logos
137}
138} ;
139
140for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
141exists(moles:dgDataEntity)
142and moles:dgMetadataID[
143moles:schemeIdentifier='NDG-B0'
144and moles:repositoryIdentifier=$repositoryIdentifier
145and moles:localIdentifier=$localIdentifier]]
146return
147utillib:strip-namespace(element dgMetadataRecord {
148    element dgMetadataID {
149        element schemeIdentifier {'NDG-B1'},
150        $DE/moles:dgMetadataID/moles:repositoryIdentifier,
151        $DE/moles:dgMetadataID/moles:localIdentifier
152    }, (: </dgMetadataID> :)
153    $DE/moles:dgMetadataDescription,
154    $DE/moles:name,
155    $DE/moles:abbreviation,
156    element dgDataEntity {
157        $DE/moles:dgDataEntity/moles:dgDataSetType,
158        $DE/moles:dgDataEntity/moles:dgDataObjectType,
159        $DE/moles:dgDataEntity/moles:dgDataGranule,
160        $DE/moles:dgDataEntity/moles:dgDataSummary,
161        element dgDataRoles {
162            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgMetadataID)) then
163                element dgDataCreator {
164                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgMetadataID,
165                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:roleName,
166                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:abbreviation,
167                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:contactDetails,
168                for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder
169                    order by $DataCreatorRole/moles:startDate empty least, $DataCreatorRole/moles:endDate empty least
170                    return
171                        element dgRoleHolder {
172                            if (exists($DataCreatorRole/moles:dgOrganisationID)) then
173                                f:return-stub-organisation('organisation', data($DataCreatorRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataCreatorRole/moles:dgOrganisationID/moles:localIdentifier))
174                             else if (exists($DataCreatorRole/moles:dgPersonID)) then
175                                f:return-stub-person('person', string($DataCreatorRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataCreatorRole/moles:dgPersonID/moles:localIdentifier))
176                             else (),
177                            $DataCreatorRole/moles:startDate,
178                            $DataCreatorRole/moles:endDate,
179                            $DataCreatorRole/moles:localName
180                        } (: </dgRoleHolder> :)
181                    } (: </dgDataCreator>) :)
182            else (),
183            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgMetadataID)) then
184                element dgDataCurator {
185                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgMetadataID,
186                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:roleName,
187                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:abbreviation,
188                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:contactDetails,
189                for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder
190                    order by $DataCuratorRole/moles:startDate empty least, $DataCuratorRole/moles:endDate empty least
191                    return
192                        element dgRoleHolder {
193                            if (exists($DataCuratorRole/moles:dgOrganisationID)) then
194                                f:return-stub-organisation('organisation', data($DataCuratorRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataCuratorRole/moles:dgOrganisationID/moles:localIdentifier))
195                             else if (exists($DataCuratorRole/moles:dgPersonID)) then
196                                f:return-stub-person('person', string($DataCuratorRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataCuratorRole/moles:dgPersonID/moles:localIdentifier))
197                             else (),
198                            $DataCuratorRole/moles:startDate,
199                            $DataCuratorRole/moles:endDate,
200                            $DataCuratorRole/moles:localName
201                        } (: </dgRoleHolder> :)
202            } (: </dgDataCurator> :)
203            else (),
204            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgMetadataID)) then
205                element dgDataOtherRoles {
206                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgMetadataID,
207                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:roleName,
208                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:abbreviation,
209                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:contactDetails,
210                for $DataOtherRolesRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgRoleHolder
211                    order by $DataOtherRolesRole/moles:startDate empty least, $DataOtherRolesRole/moles:endDate empty least
212                    return
213                        element dgRoleHolder {
214                            if (exists($DataOtherRolesRole/moles:dgOrganisationID)) then
215                                f:return-stub-organisation('organisation', data($DataOtherRolesRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataOtherRolesRole/moles:dgOrganisationID/moles:localIdentifier))
216                             else if (exists($DataOtherRolesRole/moles:dgPersonID)) then
217                                f:return-stub-person('person', string($DataOtherRolesRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataOtherRolesRole/moles:dgPersonID/moles:localIdentifier))
218                             else (),
219                            $DataOtherRolesRole/moles:startDate,
220                            $DataOtherRolesRole/moles:endDate,
221                            $DataOtherRolesRole/moles:localName
222                        } (: </dgRoleHolder> :)
223            } (: </dgDataOtherRoles> :)
224            else ()
225        } , (: </dgDataRoles> :)
226element DeploymentSummary {
227element activityList {
228for $DepActRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID/moles:repositoryIdentifier)
229for $DepActLocal in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID/moles:localIdentifier)
230let $DepAct :=  f:return-stub-activity('activity', data($DepActRepository), data($DepActLocal))
231return $DepAct
232},
233element dptList {
234for $DepDPTRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID/moles:repositoryIdentifier)
235for $DepDPTLocal in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID/moles:localIdentifier)
236let $DepDPT :=  f:return-stub-dpt('dataproductiontool', data($DepDPTRepository), data($DepDPTLocal))
237return $DepDPT
238},
239element obsStnList {
240for $DepObsStnRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID/moles:repositoryIdentifier)
241for $DepObsStnLocal in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID/moles:localIdentifier)
242let $DepObsStn :=  f:return-stub-obsstn('observationstation', data($DepObsStnRepository), data($DepObsStnLocal))
243return $DepObsStn
244}
245} (: </DeploymentSummary> :) ,
246        for $RelatedDataEntity in $DE/moles:dgDataEntity/moles:dgRelatedDataEntity
247            return
248                element relateddataentity {
249                element relation {
250                    $RelatedDataEntity/moles:RelationID/moles:dgValidTerm,
251                    $RelatedDataEntity/moles:RelationID/moles:dgValidTermID
252                }, (: </relation> :)
253                let $DE := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:repositoryIdentifier=$RelatedDataEntity/moles:RelatedDataEntityID/moles:repositoryIdentifier
254                      and moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:localIdentifier=$RelatedDataEntity/moles:RelatedDataEntityID/moles:localIdentifier]
255                 return
256                    f:return-stub-dataentity('dataentity', $DE)
257                }
258} (: </dgDataEntity> :),
259    for $strkwrd in $DE/moles:dgStructuredKeyword return $strkwrd,
260    if (exists($DE/moles:dgMetadataProvenance)) then $DE/moles:dgMetadataProvenance else (),
261    if (exists($DE/moles:dgMetadataSecurity)) then $DE/moles:dgMetadataSecurity else ()
262} (: </dgMetadataRecord> :)
263) (: end of namespace strip :)
264'''
265
266StubBActQuery = '''
267declare default element namespace 'http://ndg.nerc.ac.uk/moles/activity';
268declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
269declare namespace moles='http://ndg.nerc.ac.uk/moles';
270
271import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
272import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
273(:
274Will return when scope problem sussed... ;(
275import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
276:)
277(: replacable parameters
278declare variable $targetCollection as xs:string {'/db/ndg_B_metadata'};
279declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
280declare variable $localIdentifier as xs:string {'activity_11680365144712080'};
281:)
282declare variable $targetCollection as xs:string {'TargetCollection'};
283declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
284declare variable $localIdentifier as xs:string {'LocalID'};
285
286declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
287(: Returns a 'stubB' style activity record to expand an activity record :)
288(: Security not implemented here yet :)
289{
290let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
291moles:dgMetadataID/moles:localIdentifier=$locid
292and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
293return
294element  {$out-element-name} {
295($SRAct/moles:dgMetadataID),
296($SRAct/moles:dgMetadataDescription),
297($SRAct/moles:name),
298($SRAct/moles:abbreviation),
299($SRAct/moles:logos)
300} (: </activity> :)
301} ;
302
303declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
304(: Returns a 'stubB' style observation station record to expand an data entity record :)
305(: Security not implemented yet :)
306{
307let $SRDE := $DE
308return 
309element {$out-element-name} {
310($SRDE/moles:dgMetadataID),
311($SRDE/moles:dgMetadataDescription),
312($SRDE/moles:name),
313($SRDE/moles:abbreviation)
314} (: </dgDataEntity> :)       
315} ;
316
317declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
318(: Returns a 'stubB' style dpt record to expand a dpt record :)
319(: Security not implemented yet :)
320{
321let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
322moles:dgMetadataID/moles:localIdentifier=$locid
323and
324moles:dgMetadataID/moles:repositoryIdentifier=$repid
325]
326return 
327element {$out-element-name} {
328$SRDPT/moles:dgMetadataID,
329$SRDPT/moles:dgMetadataDescription,
330$SRDPT/moles:name,
331$SRDPT/moles:abbreviation,
332$SRDPT/moles:logos
333} (: </dataproductiontool> :)
334} ;
335
336declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
337(: Returns a 'stubB' style observation station record to expand an observation station record :)
338(: Security not implemented here yet;  :)
339{
340let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
341moles:dgMetadataID/moles:localIdentifier=$locid
342and
343moles:dgMetadataID/moles:repositoryIdentifier=$repid
344]
345return
346element {$out-element-name} {
347($SRObsStn/moles:dgMetadataID),
348($SRObsStn/moles:dgMetadataDescription),
349($SRObsStn/moles:name),
350($SRObsStn/moles:abbreviation),
351($SRObsStn/moles:logos)
352}
353} ;
354
355declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
356(: Returns a 'stubB' style observation station record to expand a person record :)
357(: Security not implemented yet :)
358{
359let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
360moles:dgMetadataID/moles:localIdentifier=$locid
361and
362moles:dgMetadataID/moles:repositoryIdentifier=$repid
363]
364return
365element  {$out-element-name}
366{
367($person/moles:name),
368($person/moles:contactDetails),
369($person/moles:dgMetadataID)
370}
371} ;
372
373declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
374(: Returns a 'stubB' style observation station record to expand an organisation record :)
375(: Security not implemented yet :)
376{
377let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
378moles:dgMetadataID/moles:localIdentifier=$locid
379and
380moles:dgMetadataID/moles:repositoryIdentifier=$repid
381]
382return
383element  {$out-element-name} {
384$org/moles:dgMetadataID,
385$org/moles:name,
386$org/moles:abbreviation,
387$org/moles:contactDetails,
388$org/moles:logos
389}
390} ;
391
392for $Act in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
393    moles:dgActivity!=''
394    and moles:dgMetadataID[
395    moles:schemeIdentifier='NDG-B0'
396    and moles:repositoryIdentifier=$repositoryIdentifier
397    and moles:localIdentifier=$localIdentifier]]
398    return
399utillib:strip-namespace(element dgMetadataRecord {
400    element dgMetadataID {
401        element schemeIdentifier {'NDG-B1'},
402        (element repositoryIdentifier {data($Act/moles:dgMetadataID/moles:repositoryIdentifier)}),
403        element localIdentifier {data($Act/moles:dgMetadataID/moles:localIdentifier)}
404    },
405    $Act/moles:dgMetadataDescription,
406    $Act/moles:name,
407    $Act/moles:abbreviation,
408    element dgActivity {
409        for $RelatedActivities in $Act/dgActivity/moles:relatedActivity
410            return
411                element relatedActivity {
412                    $RelatedActivities/moles:activityRelation,
413                    f:return-stub-activity('activity', data($RelatedActivities/moles:relatedActivityID/moles:repositoryIdentifier), data($RelatedActivities/moles:relatedActivityID/moles:localIdentifier))
414            },    (: </relatedActivity> :)
415        if (exists($Act/moles:dgActivity/moles:dgActivityDataCollection)) then ($Act/moles:dgActivity/moles:dgActivityDataCollection)
416        else if (exists($Act/moles:dgActivity/moles:dgActivityDataProject)) then ($Act/moles:dgActivity/moles:dgActivityDataProject)
417        else if (exists($Act/moles:dgActivity/moles:dgActivityDataInvestigation)) then ($Act/moles:dgActivity/moles:dgActivityDataInvestigation)
418        else if (exists($Act/moles:dgActivity/moles:dgActivityDataCampaign)) then ($Act/moles:dgActivity/moles:dgActivityDataCampaign)
419        else (),
420        element dgActivityRole {
421            element dgInvestigator {
422                element dgPrincipalInvestigator {
423                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:dgMetadataID),
424                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:roleName),
425                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:abbreviation),
426                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:contactDetails),
427                    for $PIRole in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:dgRoleHolder
428                        order by $PIRole/moles:startDate empty least, $PIRole/moles:endDate empty least
429                        return
430                        element dgRoleHolder {
431                            if (exists($PIRole/moles:dgOrganisationID)) then
432                                f:return-stub-organisation('organisation', data($PIRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($PIRole/moles:dgOrganisationID/moles:localIdentifier))
433                             else if (exists($PIRole/moles:dgPersonID)) then
434                                f:return-stub-person('person', string($PIRole/moles:dgPersonID/moles:repositoryIdentifier), string($PIRole/moles:dgPersonID/moles:localIdentifier))
435                             else (),
436                            ($PIRole/moles:startDate),
437                            if (exists($PIRole/moles:endDate)) then
438                                ($PIRole/moles:endDate)
439                            else (),
440                            if (exists($PIRole/moles:localName)) then
441                                ($PIRole/moles:localName)
442                            else ()
443                        } (: </dgRoleHolder> :)
444                }, (: </dgPrincipalInvestigator> :)
445                for $CI in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgCoInvestigator
446                return 
447                    element dgCoInvestigator {
448                        ($CI/moles:dgMetadataID),
449                        ($CI/moles:roleName),
450                        ($CI/moles:abbreviation),
451                        ($CI/moles:contactDetails),
452                        for $CIRole in $CI/moles:dgRoleHolder
453                            order by $CIRole/moles:startDate empty least, $CIRole/moles:endDate empty least
454                        return
455                        element dgRoleHolder {
456                            if (exists(CIRole/moles:dgOrganisationID)) then
457                                f:return-stub-organisation('organisation', data($CIRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($CIRole/moles:dgOrganisationID/moles:localIdentifier))
458                             else if (exists($CIRole/moles:dgPersonID)) then
459                                f:return-stub-person('person', string($CIRole/moles:dgPersonID/moles:repositoryIdentifier), string($CIRole/moles:dgPersonID/moles:localIdentifier))
460                             else (),
461                            ($CIRole/moles:startDate),
462                            if (exists($CIRole/moles:endDate)) then
463                                ($CIRole/moles:endDate)
464                            else (),
465                            if (exists($CIRole/moles:localName)) then
466                                ($CIRole/moles:localName)
467                            else ()
468                        } (: </dgRoleHolder> :)
469                } (: </dgCoInvestigator> :)
470        }, (: </dgInvestigator> :)
471        if (exists($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact)) then (
472            element dgTechnicalContact {
473                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:dgMetadataID),
474                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:roleName),
475                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:abbreviation),
476                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:contactDetails),
477                for $TechConRole in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:dgRoleHolder
478                    order by $TechConRole/moles:startDate empty least, $TechConRole/moles:endDate empty least
479                    return
480                    element dgRoleHolder {
481                        if (exists($TechConRole/moles:dgOrganisationID)) then
482                            f:return-stub-organisation('organisation', data($TechConRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($TechConRole/moles:dgOrganisationID/moles:localIdentifier))
483                         else if (exists($TechConRole/moles:dgPersonID)) then
484                            f:return-stub-person('person', string($TechConRole/moles:dgPersonID/moles:repositoryIdentifier), string($TechConRole/moles:dgPersonID/moles:localIdentifier))
485                         else (),
486                        ($TechConRole/moles:startDate),
487                        if (exists($TechConRole/moles:endDate)) then
488                            ($TechConRole/moles:endDate)
489                        else (),
490                        if (exists($TechConRole/moles:localName)) then
491                                ($TechConRole/moles:localName)
492                           else ()
493                    } (: </dgRoleHolder> :)
494            } (: </dgTechnicalContact> :)
495        )
496        else (),
497        if (exists($Act/dgActivity/dgActivityRole/dgProjectManager)) then (
498            element dgProjectManager {
499                ($Act/dgActivity/dgActivityRole/dgProjectManager/dgMetadataID),
500                ($Act/dgActivity/dgActivityRole/dgProjectManager/roleName),
501                ($Act/dgActivity/dgActivityRole/dgProjectManager/abbreviation),
502                ($Act/dgActivity/dgActivityRole/dgProjectManager/contactDetails),
503                for $PMRole in $Act/dgActivity/dgActivityRole/dgProjectManager/dgRoleHolder
504                    order by $PMRole/startDate empty least, $PMRole/endDate empty least
505                    return
506                    element dgRoleHolder {
507                        if (exists($PMRole/moles:dgOrganisationID)) then
508                            f:return-stub-organisation('organisation', data($PMRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($PMRole/moles:dgOrganisationID/moles:localIdentifier))
509                         else if (exists($PMRole/moles:dgPersonID)) then
510                            f:return-stub-person('person', string($PMRole/moles:dgPersonID/moles:repositoryIdentifier), string($PMRole/moles:dgPersonID/moles:localIdentifier))
511                         else (),
512                        ($PMRole/startDate),
513                        if (exists($PMRole/moles:endDate)) then
514                            ($PMRole/moles:endDate)
515                        else (),
516                        if (exists($PMRole/moles:localName)) then
517                            ($PMRole/moles:localName)
518                        else ()
519                    } (: </dgRoleHolder> :)
520            } (: </dgProjectManager> :)
521        )
522        else ()
523    }, (: </dgActivityRole> :)
524element DeploymentSummary {
525element dptList {
526for $DepDPTRepository in distinct-values($Act/moles:dgActivity/moles:ActivityDeployment/moles:DataProductionToolID/moles:repositoryIdentifier)
527for $DepDPTLocal in distinct-values($Act/moles:dgActivity/moles:ActivityDeployment/moles:DataProductionToolID/moles:localIdentifier)
528let $DepDPT :=  f:return-stub-dpt('dataproductiontool', data($DepDPTRepository), data($DepDPTLocal))
529return $DepDPT
530},
531element obsStnList {
532for $DepObsStnRepository in distinct-values($Act/moles:dgActivity/moles:ActivityDeployment/moles:ObservationStationID/moles:repositoryIdentifier)
533for $DepObsStnLocal in distinct-values($Act/moles:dgActivity/moles:ActivityDeployment/moles:DataProductionToolID/moles:localIdentifier)
534let $DepObsStn :=  f:return-stub-obsstn('observationstation', data($DepObsStnRepository), data($DepObsStnLocal))
535return $DepObsStn
536},
537element dataEntityList {
538for $DE in
539collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment
540/moles:DataProductionToolID
541[moles:localIdentifier=$Act/moles:dgMetadataID/moles:localIdentifier
542and moles:repositoryIdentifier=$Act/moles:dgMetadataID/moles:repositoryIdentifier]]
543order by $DE/moles:dgMetadataID
544return f:return-stub-dataentity('dataentity', $DE)
545}
546}, (: </DeploymentSummary> :)
547        if (exists($Act/dgActivityCoverage)) then
548            ($Act/dgActivityCoverage)
549            else (),
550        if (exists($Act/dgActivityDuration)) then
551            ($Act/dgActivityDuration)
552            else ()
553    } , (: </dgActivity> :)
554    for $strkwrd in $Act/moles:dgStructuredKeyword return $strkwrd,
555    if (exists($Act/moles:dgMetadataProvenance)) then $Act/moles:dgMetadataProvenance else (),
556    if (exists($Act/moles:dgMetadataSecurity)) then $Act/moles:dgMetadataSecurity else ()
557} (:</dgMRecord>:)
558) (: End namespace strip :)
559'''
560
561StubBDPTQuery = '''
562declare default element namespace 'http://ndg.nerc.ac.uk/moles/dataproductiontool';
563import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
564import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
565(:
566Will return when scope problem sussed... ;(
567import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
568:)
569declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
570declare namespace moles='http://ndg.nerc.ac.uk/moles';
571
572(: replacable parameters
573declare variable $targetCollection as xs:string {'/db/ndg_B_metadata'};
574declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
575declare variable $localIdentifier as xs:string {'dpt_116291244849226'};
576:)
577declare variable $targetCollection as xs:string {'TargetCollection'};
578declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
579declare variable $localIdentifier as xs:string {'LocalID'};
580
581declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
582(: Returns a 'stubB' style activity record to expand an activity record :)
583(: Security not implemented here yet :)
584{
585let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
586moles:dgMetadataID/moles:localIdentifier=$locid
587and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
588return
589element  {$out-element-name} {
590($SRAct/moles:dgMetadataID),
591($SRAct/moles:dgMetadataDescription),
592($SRAct/moles:name),
593($SRAct/moles:abbreviation),
594($SRAct/moles:logos)
595} (: </activity> :)
596} ;
597
598declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
599(: Returns a 'stubB' style observation station record to expand an data entity record :)
600(: Security not implemented yet :)
601{
602let $SRDE := $DE
603return 
604element {$out-element-name} {
605($SRDE/moles:dgMetadataID),
606($SRDE/moles:dgMetadataDescription),
607($SRDE/moles:name),
608($SRDE/moles:abbreviation)
609} (: </dgDataEntity> :)       
610} ;
611
612declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
613(: Returns a 'stubB' style dpt record to expand a dpt record :)
614(: Security not implemented yet :)
615{
616let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
617moles:dgMetadataID/moles:localIdentifier=$locid
618and
619moles:dgMetadataID/moles:repositoryIdentifier=$repid
620]
621return 
622element {$out-element-name} {
623$SRDPT/moles:dgMetadataID,
624$SRDPT/moles:dgMetadataDescription,
625$SRDPT/moles:name,
626$SRDPT/moles:abbreviation,
627$SRDPT/moles:logos
628} (: </dataproductiontool> :)
629} ;
630
631declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
632(: Returns a 'stubB' style observation station record to expand an observation station record :)
633(: Security not implemented here yet;  :)
634{
635let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
636moles:dgMetadataID/moles:localIdentifier=$locid
637and
638moles:dgMetadataID/moles:repositoryIdentifier=$repid
639]
640return
641element {$out-element-name} {
642($SRObsStn/moles:dgMetadataID),
643($SRObsStn/moles:dgMetadataDescription),
644($SRObsStn/moles:name),
645($SRObsStn/moles:abbreviation),
646($SRObsStn/moles:logos)
647}
648} ;
649
650declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
651(: Returns a 'stubB' style observation station record to expand a person record :)
652(: Security not implemented yet :)
653{
654let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
655moles:dgMetadataID/moles:localIdentifier=$locid
656and
657moles:dgMetadataID/moles:repositoryIdentifier=$repid
658]
659return
660element  {$out-element-name}
661{
662($person/moles:name),
663($person/moles:contactDetails),
664($person/moles:dgMetadataID)
665}
666} ;
667
668declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
669(: Returns a 'stubB' style observation station record to expand an organisation record :)
670(: Security not implemented yet :)
671{
672let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
673moles:dgMetadataID/moles:localIdentifier=$locid
674and
675moles:dgMetadataID/moles:repositoryIdentifier=$repid
676]
677return
678element  {$out-element-name} {
679$org/moles:dgMetadataID,
680$org/moles:name,
681$org/moles:abbreviation,
682$org/moles:contactDetails,
683$org/moles:logos
684}
685} ;
686
687for $DPT in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
688    moles:dgDataProductionTool!=''
689    and moles:dgMetadataID[
690    moles:schemeIdentifier='NDG-B0'
691    and moles:repositoryIdentifier=$repositoryIdentifier
692    and moles:localIdentifier=$localIdentifier]]
693    return
694utillib:strip-namespace(element dgMetadataRecord {
695    $DPT/dgMetadataID,
696        element dgMetadataID {
697            element schemeIdentifier {'NDG-B1'},
698            $DPT/moles:dgMetadataID/moles:repositoryIdentifier,
699            $DPT/moles:dgMetadataID/moles:localIdentifier
700        } (: End </dgMetadataID> :),
701    $DPT/moles:dgMetadataDescription,
702    $DPT/moles:name,
703    $DPT/moles:abbreviation,
704    element dgDataProductionTool {
705        $DPT/moles:contactDetails,
706        if (exists($DPT/moles:dgModel)) then $DPT/moles:dgModel
707        else $DPT/moles:dgInstrument
708    ,
709    if (exists($DPT/moles:dgDPTRoles)) then
710        element dgDPTRoles {'Roles are available, and will be added soon'}
711     else(),
712element DeploymentSummary {
713element activityList {
714for $DepActRepository in distinct-values($DPT/moles:dgDataProductionTool/moles:DPTDeployment/moles:ActivityID/moles:repositoryIdentifier)
715for $DepActLocal in distinct-values($DPT/moles:dgDataProductionTool/moles:DPTDeployment/moles:ActivityID/moles:localIdentifier)
716let $DepAct :=  f:return-stub-activity('activity', data($DepActRepository), data($DepActLocal))
717return $DepAct
718},
719element obsStnList {
720for $DepObsStnRepository in distinct-values($DPT/moles:dgDataProductionTool/moles:DPTDeployment/moles:ObservationStationID/moles:repositoryIdentifier)
721for $DepObsStnLocal in distinct-values($DPT/moles:dgDataProductionTool/moles:DPTDeployment/moles:DataProductionToolID/moles:localIdentifier)
722let $DepObsStn :=  f:return-stub-obsstn('observationstation', data($DepObsStnRepository), data($DepObsStnLocal))
723return $DepObsStn
724},
725element dataEntityList {
726for $DE in
727collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment
728/moles:DataProductionToolID
729[moles:localIdentifier=$DPT/moles:dgMetadataID/moles:localIdentifier
730and moles:repositoryIdentifier=$DPT/moles:dgMetadataID/moles:repositoryIdentifier]]
731order by $DE/moles:dgMetadataID
732return f:return-stub-dataentity('dataentity', $DE)
733}
734} (: </DeploymentSummary> :)
735} (: </dgDataProductionTool> :),
736    for $strkwrd in $DPT/moles:dgStructuredKeyword return $strkwrd,
737    if (exists($DPT/moles:dgMetadataProvenance)) then $DPT/moles:dgMetadataProvenance else (),
738    if (exists($DPT/moles:dgMetadataSecurity)) then $DPT/moles:dgMetadataSecurity else ()
739} (:End </dgMetadataRecord> :)
740) (: End namespace strip :)
741'''
742
743StubBObsStnQuery = '''
744declare default element namespace 'http://ndg.nerc.ac.uk/moles/observationstation';
745import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
746import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
747(:
748Will return when scope problem sussed... ;(
749import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
750:)
751declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
752declare namespace moles='http://ndg.nerc.ac.uk/moles';
753
754(: replacable parameters
755declare variable $targetCollection as xs:string {'/db/ndg_B_metadata_4'};
756declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
757declare variable $localIdentifier as xs:string {'obs_1162914661529326'};
758:)
759declare variable $targetCollection as xs:string {'TargetCollection'};
760declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
761declare variable $localIdentifier as xs:string {'LocalID'};
762declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
763(: Returns a 'stubB' style activity record to expand an activity record :)
764(: Security not implemented here yet :)
765{
766let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
767moles:dgMetadataID/moles:localIdentifier=$locid
768and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
769return
770element  {$out-element-name} {
771($SRAct/moles:dgMetadataID),
772($SRAct/moles:dgMetadataDescription),
773($SRAct/moles:name),
774($SRAct/moles:abbreviation),
775($SRAct/moles:logos)
776} (: </activity> :)
777} ;
778
779declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
780(: Returns a 'stubB' style observation station record to expand an data entity record :)
781(: Security not implemented yet :)
782{
783let $SRDE := $DE
784return 
785element {$out-element-name} {
786($SRDE/moles:dgMetadataID),
787($SRDE/moles:dgMetadataDescription),
788($SRDE/moles:name),
789($SRDE/moles:abbreviation)
790} (: </dgDataEntity> :)       
791} ;
792
793declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
794(: Returns a 'stubB' style dpt record to expand a dpt record :)
795(: Security not implemented yet :)
796{
797let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
798moles:dgMetadataID/moles:localIdentifier=$locid
799and
800moles:dgMetadataID/moles:repositoryIdentifier=$repid
801]
802return 
803element {$out-element-name} {
804$SRDPT/moles:dgMetadataID,
805$SRDPT/moles:dgMetadataDescription,
806$SRDPT/moles:name,
807$SRDPT/moles:abbreviation,
808$SRDPT/moles:logos
809} (: </dataproductiontool> :)
810} ;
811
812declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
813(: Returns a 'stubB' style observation station record to expand an observation station record :)
814(: Security not implemented here yet;  :)
815{
816let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
817moles:dgMetadataID/moles:localIdentifier=$locid
818and
819moles:dgMetadataID/moles:repositoryIdentifier=$repid
820]
821return
822element {$out-element-name} {
823($SRObsStn/moles:dgMetadataID),
824($SRObsStn/moles:dgMetadataDescription),
825($SRObsStn/moles:name),
826($SRObsStn/moles:abbreviation),
827($SRObsStn/moles:logos)
828}
829} ;
830
831declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
832(: Returns a 'stubB' style observation station record to expand a person record :)
833(: Security not implemented yet :)
834{
835let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
836moles:dgMetadataID/moles:localIdentifier=$locid
837and
838moles:dgMetadataID/moles:repositoryIdentifier=$repid
839]
840return
841element  {$out-element-name}
842{
843($person/moles:name),
844($person/moles:contactDetails),
845($person/moles:dgMetadataID)
846}
847} ;
848
849declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
850(: Returns a 'stubB' style observation station record to expand an organisation record :)
851(: Security not implemented yet :)
852{
853let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
854moles:dgMetadataID/moles:localIdentifier=$locid
855and
856moles:dgMetadataID/moles:repositoryIdentifier=$repid
857]
858return
859element  {$out-element-name} {
860$org/moles:dgMetadataID,
861$org/moles:name,
862$org/moles:abbreviation,
863$org/moles:contactDetails,
864$org/moles:logos
865}
866} ;
867
868let $ObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
869moles:dgObservationStation!=''
870and moles:dgMetadataID[
871moles:repositoryIdentifier=$repositoryIdentifier
872and moles:localIdentifier=$localIdentifier]]
873return
874utillib:strip-namespace(
875element dgMetadataRecord {
876element dgMetadataID {
877element schemeIdentifier {'NDG-B1'},
878$ObsStn/moles:dgMetadataID/moles:repositoryIdentifier,
879$ObsStn/moles:dgMetadataID/moles:localIdentifier
880} (: End </dgMetadataID> :),
881$ObsStn/moles:dgMetadataDescription,
882$ObsStn/moles:name,
883$ObsStn/moles:abbreviation,
884element dgObservationStation {
885$ObsStn/moles:dgObservationStation/moles:contactDetails,
886if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform)) then
887element dgStationaryPlatform {
888$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:position,
889if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring)) then   
890element dgMooring {
891$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dateStart,
892$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dateEnd,
893for $DepositingCruise in $ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:DepositingCruise
894return
895f:return-stub-activity('depositingcruise', data($DepositingCruise/moles:dgMetadataID/moles:repositoryIdentifier), data($DepositingCruise/moles:dgMetadataID/moles:localIdentifier)),
896if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dgStationGrouping)) then   
897for $StationGrouping in $ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/dgStationGrouping
898return 
899f:return-stub-obsstn('dgStationGrouping', data($StationGrouping/moles:dgMetadataID/moles:repositoryIdentifier), data($StationGrouping/moles:dgMetadataID/moles:localIdentifier))
900else ()
901} (: End </dgMooring> :) 
902else if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup)) then   
903element dgStationGroup {
904element dgGroupedStations {
905if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStations)) then
906for $GroupedStation in $ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStation/dgGroupedStations
907return f:return-stub-obsstn('dgGroupedStation', data($GroupedStation/moles:dgMetadataID/moles:repositoryIdentifier), data($GroupedStation/moles:dgMetadataID/moles:localIdentifier))
908else ()
909} (: End </dgGroupedStations> :)
910} (: End </dgStationGroup> :)
911else $ObsStn/moles:dgObservationStation/moles:dgLandStation
912} (: End </dgStationaryPlatform>  :) 
913else $ObsStn/moles:dgObservationStation/moles:dgMovingPlatform ,
914element DeploymentSummary {
915element activityList {
916for $DepActRepository in distinct-values($ObsStn/moles:dgObservationStation/moles:ObsStationDeployment/moles:ActivityID/moles:repositoryIdentifier)
917for $DepActLocal in distinct-values($ObsStn/moles:dgObservationStation/moles:ObsStationDeployment/moles:ActivityID/moles:localIdentifier)
918let $DepAct :=  f:return-stub-activity('activity', data($DepActRepository), data($DepActLocal))
919return $DepAct
920},
921element dptList {
922for $DepDPTRepository in distinct-values($ObsStn/moles:dgObservationStation/moles:ObsStationDeployment/moles:DataProductionToolID/moles:repositoryIdentifier)
923for $DepDPTLocal in distinct-values($ObsStn/moles:dgObservationStation/moles:ObsStationDeployment/moles:DataProductionToolID/moles:localIdentifier)
924let $DepDPT :=  f:return-stub-dpt('dataproductiontool', data($DepDPTRepository), data($DepDPTLocal))
925return $DepDPT
926},
927element dataEntityList {
928for $DE in
929collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment
930/moles:ObservationStationID
931[moles:localIdentifier=$ObsStn/moles:dgMetadataID/moles:localIdentifier
932and moles:repositoryIdentifier=$ObsStn/moles:dgMetadataID/moles:repositoryIdentifier]]
933order by $DE/moles:dgMetadataID
934return f:return-stub-dataentity('dataentity', $DE)
935}
936} (: </DeploymentSummary> :)
937} (: </dgObservationStation> :),
938for $strkwrd in $ObsStn/moles:dgStructuredKeyword return $strkwrd,
939if (exists($ObsStn/moles:dgMetadataProvenance)) then $ObsStn/moles:dgMetadataProvenance else (),
940if (exists($ObsStn/moles:dgMetadataSecurity)) then $ObsStn/moles:dgMetadataSecurity else ()
941} (: End </dgMetadataRecord> :)
942) (: End namespace strip :)
943'''
944
945ISO19139Query = '''
946import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
947import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
948
949declare default element namespace 'http://www.isotc211.org/2005/gmd';
950declare namespace moles='http://ndg.nerc.ac.uk/moles';
951declare namespace gco='http://www.isotc211.org/2005/gco';
952declare namespace gmd='http://www.isotc211.org/2005/gmd';
953declare namespace gml='http://www.opengis.net/gml';
954declare namespace xlink='http://www.w3.org/1999/xlink';
955declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
956declare option exist:timeout '24500';
957
958declare variable $targetCollection as xs:string {'TargetCollection'};
959declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
960declare variable $localIdentifier as xs:string {'LocalID'};
961
962for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
963    exists(moles:dgDataEntity)
964    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
965    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
966return
967element MD_Metadata {
968    attribute xsi:schemaLocation {'http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/metadataEntity.xsd'},
969    element fileIdentifier {element gco:CharacterString {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'ISO19115', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)}},
970    element language {
971        element gmd:LanguageCode {
972            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},
973            attribute codeListValue {'eng'},
974            'English'}
975    } (: </language> :),
976    element hierarchyLevel {
977        element MD_ScopeCode {
978            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode'},
979            attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode_dataset'},
980            'dataset'}
981    } (: </hierarchyLevel> :),
982    for $parent in $DE/moles:dgRelatedDataEntity[moles:RelationID/moles:dgValidTerm='is-part-of']
983    return
984        element parentIdentifier  {element gco:CharacterString {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, ':', $DE/moles:dgMetadataID/moles:localIdentifier, ':', $DE/moles:dgMetadataID/moles:localIdentifier)}},
985    for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate='']
986    return
987        for $DataCuratorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgPerson | moles:dgOrganisation)[
988            moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
989            and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/(moles:dgPersonID | moles:dgOrganisationID)/moles:repositoryIdentifier
990            and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/(moles:dgPersonID | moles:dgOrganisationID)/moles:localIdentifier]
991        return
992            element contact {
993                element CI_ResponsibleParty {
994                    if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then
995                        element organisationName {element gco:CharacterString {string($DataCuratorRoleHolder/moles:name)}}
996                    else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then
997                        element individualName {element gco:CharacterString {string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))}}
998                    else ('empty content') ,     
999                    element positionName {
1000                        if (exists($DataCuratorRoleHolder/moles:localName)) then
1001                            element gco:CharacterString {$DataCuratorRoleHolder/moles:localName}
1002                        else if (exists($DataCuratorRole/moles:roleName)) then
1003                            element gco:CharacterString {$DataCuratorRole/moles:roleName}
1004                        else
1005                            element gco:CharacterString {'Curator'}
1006                    } (: </positionName>:),
1007                    element contactInfo {
1008                        element gmd:CI_Contact {
1009                            if (exists($DataCuratorRole/moles:contactDetails/moles:telephone
1010                                or $DataCuratorRole/moles:contactDetails/moles:fax
1011                                or $DataCuratorRoleHolder/moles:contactDetails/moles:telephone
1012                                or $DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then
1013                                element phone {
1014                                    element gmd:CI_Telephone {
1015                                        if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then
1016                                            element voice {
1017                                                element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:telephone)}
1018                                            } (:</voice>:)
1019                                        else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
1020                                            element voice {
1021                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)}
1022                                            } (:</voice>:)
1023                                        else (),
1024                                        if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then
1025                                            element facsimile {
1026                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
1027                                            } (: </facsimile> :)
1028                                        else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
1029                                            element facsimile {
1030                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
1031                                            } (: </facsimile> :)
1032                                        else ()
1033                                    } (: </gmd:CI_Telephone> :)
1034                                } (: </phone> :)
1035                                                    else (),
1036                            element address {
1037                                element gmd:CI_Address {
1038                                    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:addressline)) then                               
1039                                        for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline
1040                                        return
1041                                            element deliveryPoint {element gco:CharacterString {data($addressline)}}
1042                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline)) then
1043                                        for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline
1044                                        return
1045                                            element deliveryPoint {element gco:CharacterString {data($addressline)}}
1046                                    else (),
1047                                    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then
1048                                        element city {element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:address/moles:city)}}
1049                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then
1050                                        element city {element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)}}
1051                                    else (),
1052                                    if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then
1053                                        element electronicMailAddress {element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:eMail)}}
1054                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then
1055                                        element electronicMailAddress {element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)}}
1056                                    else ()
1057                                } (: </gmd:CI_Address> :)
1058                            } (: </address> :)
1059                        } (: </gmd:CI_Contact> :)
1060                    } (: </contactInfo> :),
1061                    element role {
1062                        element CI_RoleCode {
1063                            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode'},
1064                            attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode_custodian'},
1065                            if (exists($DataCuratorRole/moles:localName)) then                               
1066                                data($DataCuratorRole/moles:localName)
1067                            else if (exists($DataCuratorRoleHolder/moles:localName)) then
1068                                data($DataCuratorRoleHolder/moles:localName)
1069                            else 'Curator' 
1070                        } (: </CI_RoleCode> :)
1071                    } (: </role> :)
1072                } (: </CI_ResponsibleParty> :)
1073            } (: </contact> :),
1074
1075            element dateStamp {element gco:Date {adjust-date-to-timezone(current-date())}},
1076            element metadataStandardName {element gco:CharacterString {'ISO 19115:2003'}},
1077            element metadataStandardVersion {element gco:CharacterString {'2003'}},
1078            element identificationInfo {
1079                element gmd:MD_DataIdentification {
1080                    element citation {
1081                        element gmd:CI_Citation {
1082                            element title {element gco:CharacterString {data($DE/moles:name)}},
1083                            if (exists($DE/moles:abbreviation) and not(empty($DE/moles:abbreviation))) then
1084                                element alternateTitle {element gco:CharacterString {data($DE/moles:abbreviation)}}
1085                            else (),
1086                            element date {
1087                                if (exists($DE/(moles:DataProvenance | moles:dgMetadataProvenance)/moles:RecordCreation/moles:CreatedDate)) then
1088                                    element gmd:CI_Date {
1089                                        element date {element gco:Date {adjust-date-to-timezone(data($DE/(moles:DataProvenance | moles:dgMetadataProvenance)/moles:RecordCreation/moles:CreatedDate))}},
1090                                        element dateType {
1091                                            element CI_DateTypeCode {
1092                                                attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode'},
1093                                                attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode_creation' },
1094                                                'Creation'}
1095                                        } (: </dataType> :)
1096                                    } (: </gmd:CI_Date> :)
1097                                else
1098                                    attribute gco:nilReason {'unknown'}
1099                            } (: </date> :)
1100                        } (: </gmd:CI_Citation> :)
1101                    } (: </citation> :),
1102                    element abstract {element gco:CharacterString {data($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)}},
1103                    element language {
1104                        element gmd:LanguageCode {
1105                            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},
1106                            attribute codeListValue {'eng'},
1107                            'English' }
1108                    } (: </language> :),
1109                    for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[dgValidTermID/moles:ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'])
1110                    return
1111                        element topicCategory {
1112                            element gmd:MD_TopicCategoryCode {
1113                                attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'},
1114                                attribute codeListValue {string($ISOTopicCategory/moles:dgValidTerm)},
1115                                string($ISOTopicCategory/moles:dgValidTerm)}
1116                        } (: </topicCategory> :),
1117                    if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage)) then
1118                        element extent {
1119                            element gmd:EX_Extent {
1120                                (: add bounding boxes:)
1121                                for $geoBBox in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:BoundingBox
1122                                return
1123                                    element geographicElement {
1124                                        element EX_GeographicBoundingBox {
1125                                            element westBoundLongitude {element gco:Decimal {data($geoBBox/moles:LimitWest)}},
1126                                            element eastBoundLongitude {element gco:Decimal {data($geoBBox/moles:LimitEast)}},
1127                                            element southBoundLatitude {element gco:Decimal {data($geoBBox/moles:LimitSouth)}},
1128                                            element northBoundLatitude {element gco:Decimal {data($geoBBox/moles:LimitNorth)}}
1129                                        } (: </EX_GeographicBoundingBox> :)
1130                                    } (: </geographicElement> :),
1131                                (: add location terms:)
1132                                for $geoArea in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea
1133                                return
1134                                    element geographicElement {
1135                                        element EX_GeographicDescription {
1136                                            element geographicIdentifier {
1137                                                element gmd:RS_Identifier {
1138                                                element gco:CharacterString {element code {data($geoArea/moles:dgValidTerm)}},
1139                                                element gco:CharacterString {element codeSpace {data($geoArea/moles:dgValidTermID/moles:ParentListID)}}
1140                                                    }
1141                                                }
1142                                        } (: </EX_GeographicDescription> :)
1143                                    } (: </geographicElement> :)
1144                            } (: </gmd:EX_Extent> :)
1145                        } (: </extent> :)
1146                    else()
1147                } (:</gmd:MD_DataIdentification> :)
1148            } (: </identificationInfo> :)
1149} (: </MD_Metadata> :)'''
1150           
1151MOLESQuery = '''declare default element namespace 'http://ndg.nerc.ac.uk/moles';
1152declare variable $targetCollection as xs:string {'TargetCollection'};
1153declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1154declare variable $localIdentifier as xs:string {'LocalID'};
1155for $Moles in collection($targetCollection)/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0'
1156    and dgMetadataID/repositoryIdentifier=$repositoryIdentifier
1157    and dgMetadataID/localIdentifier=$localIdentifier]
1158    return $Moles '''
1159           
1160DIFQuery = '''
1161import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1162import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1163(: Keep
1164declare default element namespace 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/';
1165declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1166declare namespace moles='http://ndg.nerc.ac.uk/moles';
1167:)
1168declare variable $targetCollection as xs:string {'TargetCollection'};
1169declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1170declare variable $localIdentifier as xs:string {'LocalID'};
1171declare variable $targetCollection as xs:string {'/db/ndg_B_metadata'};
1172declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
1173declare variable $localIdentifier as xs:string {'dataent_chablis'};
1174
1175let $DE := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
1176    exists('moles:dgDataEntity')
1177    and moles:dgMetadataID/moles:repositoryIdentifier=$repositoryIdentifier
1178    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
1179    return
1180element DIF {
1181    attribute xsi:schemaLocation {'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/ http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif_v9.4.xsd'},
1182    element Entry_ID {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'DIF', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)},
1183    element Entry_Title {string($DE/moles:name)},
1184    element Data_Set_Citation {
1185            for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''][1]
1186        return
1187            for $DataCreatorRoleHolder in collection($targetCollection)/moles:dgMetadata/(dgOrganisation | dgPerson)[(
1188                   moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:repositoryIdentifier
1189                   and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:localIdentifier)]
1190            return
1191                    element Dataset_Creator {
1192                if (exists($DataCreatorRoleHolder/moles:name/moles:initials)) then
1193                    string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName)))
1194                else
1195                   string($DataCreatorRoleHolder/moles:abbreviation)
1196                    },
1197        element Dataset_Title {string($DE/moles:name)}
1198    },
1199    for $StructuredKeyword in ($DE/(moles:dgStructuredKeyword | moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured)[(voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_categories, moles:dgValidTermID/moles:ParentListID))]
1200    )
1201        return if (exists($StructuredKeyword/*/moles:dgValidTerm)) then
1202            element Parameters {
1203            element Category {string($StructuredKeyword/*/moles:dgValidTerm)},
1204            if (exists($StructuredKeyword/*/moles:dgValidSubterm)
1205                and $StructuredKeyword/*/moles:dgValidSubterm != ''
1206                and $StructuredKeyword/*/moles:dgValidSubterm != ' ') then
1207            for $Subterm in $StructuredKeyword//moles:dgValidSubterm[exists(moles:dgValidTerm)]
1208                where exists($Subterm/moles:dgValidSubterm)
1209                order by $Subterm/moles:ListLevel
1210                return
1211                    if ($Subterm/moles:ListLevel=1) then element Topic {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1212                    else if ($Subterm/moles:ListLevel=2) then element Term {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1213                    else if ($Subterm/moles:ListLevel=3) then element Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1214                    else if ($Subterm/moles:ListLevel=4) then element Detailed_Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1215                    else element GCMD_Science_Valid {data($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1216            else()
1217                }
1218        else(),
1219    for $StructuredKeyword in ($DE/(moles:dgStructuredKeyword | moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured)[voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_deprecated, moles:dgValidTermID/moles:ParentListID) and (not(exists(moles:ListLevel)) or moles:ListLevel=0)])
1220    return
1221        element Parameters {data($StructuredKeyword/moles:dgValidTerm)},
1222    for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)])
1223        return
1224            element ISO_Topic_Category {string($ISOTopicCategory/moles:dgValidTerm)},
1225    for $Keyword in distinct-values($DE/moles:dgStructuredKeyword[
1226    not (voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)
1227    or voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID)
1228    or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID)
1229    or voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)
1230    )]/moles:dgValidTerm)
1231    return element Keyword {string($Keyword)},
1232    for $DepDPTRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID/moles:repositoryIdentifier) 
1233    for $DepDPTLocal in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID[moles:repositoryIdentifier=$DepDPTRepository]/moles:localIdentifier) 
1234    let $DepDPTRecord := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPTRepository  and moles:localIdentifier=$DepDPTLocal]]
1235                return
1236                        element Sensor_Name {
1237                element Short_Name {data($DepDPTRecord/moles:abbreviation)},
1238                element Long_Name {data($DepDPTRecord/moles:name)}
1239            },
1240    for $DepObsStnRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID/moles:repositoryIdentifier)
1241    for $DepObsStnLocal in distinct-values(($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID[moles:repositoryIdentifier=$DepObsStnRepository]/moles:localIdentifier))
1242    let $DepObsStnRecord := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:repositoryIdentifier=$DepObsStnRepository  and moles:localIdentifier=$DepObsStnLocal]]
1243                return element Source_Name {
1244                element Short_Name {data($DepObsStnRecord/moles:abbreviation)},
1245                element Long_Name {data($DepObsStnRecord/moles:name)}
1246            },
1247    for $TemporalRange in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage/(moles:dgTemporalCoverage | moles:dgSpatioTemporalCoverage/moles:dgSpatioTemporalRange/moles:dgTemporalCoverage)/moles:DateRange
1248        return
1249            element Temporal_Coverage
1250                {
1251                element Start_Date {data($TemporalRange/moles:DateRangeStart)},
1252                element End_Date {data($TemporalRange/moles:DateRangeEnd)}
1253                },
1254    for $TemporalTerm in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage/(moles:dgTemporalCoverage | moles:dgSpatioTemporalCoverage/moles:dgSpatioTemporalRange/moles:dgTemporalCoverage)/moles:dgChronostratigraphicTerm[voclib:spot-vocab($voclib:gcmd_chronostratigraphic_valids, moles:dgValidTermID/moles:ParentListID)]/moles:dgValidTerm
1255        return element Paleo_Temporal_Coverage {element Chronostratigraphic_Unit {data($TemporalTerm)}},
1256    for $Data_Set_Progress in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataStatus/moles:dgDatasetClosure)
1257        return element Data_Set_Progress {data($Data_Set_Progress)},
1258    for $BoundingBox in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage/(moles:dgSpatialCoverage | moles:dgSpatioTemporalCoverage/moles:dgSpatioTemporalRange/moles:dgSpatialCoverage)/moles:BoundingBox
1259    return
1260        element Spatial_Coverage {
1261                element Southernmost_Latitude {data($BoundingBox/moles:LimitSouth)},
1262                element Northernmost_Latitude {data($BoundingBox/moles:LimitNorth)},
1263                element Westernmost_Longitude {data($BoundingBox/moles:LimitWest)},
1264                element Easternmost_Longitude {data($BoundingBox/moles:LimitEast)}
1265            },
1266    for $Location in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage/(moles:dgSpatialCoverage | moles:dgSpatioTemporalCoverage/moles:dgSpatioTemporalRange/moles:dgSpatialCoverage)/moles:dgArea[voclib:spot-vocab($voclib:gcmd_location_valids, moles:dgValidTermID/moles:ParentListID)])
1267        return element Location {data($Location/moles:dgValidTerm)},
1268    for $DepActRepository in distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID/moles:repositoryIdentifer)
1269    for $DepActLocal in  distinct-values($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID[moles:repositoryIdentifer=$DepActRepository]/moles:localIdentifer) 
1270    let $DepActRecord := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:repositoryIdentifier=$DepActRepository and moles:localIdentifier=$DepActLocal]]
1271    return
1272        element Project {
1273                    element Short_Name {data($DepActRecord/abbreviation)},
1274                    element Long_Name {data($DepActRecord/name)}
1275            },
1276    if (exists($DE/moles:dgDataEntity/moles:dgDataGranule/moles:accessControlPolicy)) then
1277            for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule
1278                return
1279                                element Access_Constraints {
1280                            if (exists($DG/moles:dgGranuleSummary/moles:dgGranuleName)) then
1281                                concat('For data granule ', $DG/moles:dgGranuleSummary/moles:dgGranuleName, ': ')
1282                            else (),
1283                            if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyURL)) then
1284                                concat('See access control policy at ', escape-uri($DG/moles:accessControlPolicy/moles:accessControlPolicyURL, true()))
1285                            else if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyText)) then
1286                                data($DG/moles:accessControlPolicy/moles:accessControlPolicyText)
1287                             else
1288                                 for $securityCondition in $DG/moles:accessControlPolicy/moles:dgSecurityCondition
1289                                 return
1290                                     if (exists($securityCondition/moles:conditionExplanationText)) then
1291                                         concat('Effect: ', data($securityCondition/moles:effect), ' - ', data($securityCondition/moles:conditionExplanationText))
1292                                     else concat('Effect: ', data($securityCondition/moles:effect), 'needs ', data($securityCondition/moles:attauthRole), ' from ', data($securityCondition/moles:dgAttributeAuthority))
1293                        }
1294                else (),
1295    if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder)) then
1296        for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder
1297            order by $DataCreatorRole/moles:startDate empty least
1298                        return
1299                    for $DataCreatorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson)
1300                                        [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1301                                        and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/*/moles:repositoryIdentifier
1302                                        and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/*/moles:localIdentifier)]
1303                    return
1304                            element Originating_Center {
1305                    if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then
1306                        (string($DataCreatorRoleHolder/moles:name))
1307                    else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then
1308                        (string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName))))
1309                    else ('empty content')
1310                }
1311    else (),
1312    for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder
1313    [not(exists(moles:endDate)) or moles:endDate='']
1314    return
1315    for $DataCuratorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson)
1316    [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1317    and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/*/moles:repositoryIdentifier
1318    and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/*/moles:localIdentifier)]
1319    return
1320    element Data_Center {
1321    element Data_Center_Name {
1322    element Short_Name {
1323    if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1324    string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))
1325    else
1326    string($DataCuratorRoleHolder/moles:abbreviation)
1327    },
1328    element Long_Name {
1329    if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1330    string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))
1331    else string($DataCuratorRoleHolder/moles:name)
1332    }
1333    },
1334    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:URI)) then
1335    element Data_Center_URL {data($DataCuratorRoleHolder/moles:contactDetails/moles:URI)}
1336    else (),
1337    for $DGID in $DE/moles:dgDataEntity/moles:dgDataGranule/moles:dataModelID
1338    return
1339    element Data_Set_ID {concat($DGID/moles:repositoryIdentifier, $utillib:moles_id_separator, $DGID/moles:schemeIdentifier, $utillib:moles_id_separator, $DGID/moles:localIdentifier)},
1340    element  Personnel {
1341    element Role {'Data Center Contact'},
1342    if (exists($DataCuratorRoleHolder/name/knownAs)) then
1343    element First_Name {string($DataCuratorRoleHolder/moles:name/moles:knownAs)}
1344    else if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1345    element First_Name {string($DataCuratorRoleHolder/moles:name/moles:initials)}
1346    else (),                   
1347    element Last_Name {
1348    if (exists($DataCuratorRoleHolder/moles:name/moles:familyName)) then
1349    string($DataCuratorRoleHolder/moles:name/moles:familyName)
1350    else string($DataCuratorRoleHolder/moles:name)
1351    },
1352    if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then
1353    element Email {string($DataCuratorRole/moles:contactDetails/moles:eMail)}
1354    else
1355    if (exists($DataCuratorRoleHolder/contactDetails/eMail)) then
1356    (element Email {string($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)})
1357    else (),
1358    if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then
1359    element Phone {string($DataCuratorRole/moles:contactDetails/moles:telephone)}
1360    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
1361    element Phone {string($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)}
1362    else (),
1363    if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then
1364    element Fax {string($DataCuratorRole/moles:contactDetails/moles:fax)}
1365    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then
1366    element Fax {string($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
1367    else (),
1368    if (exists($DataCuratorRole/moles:contactDetails/moles:address)) then
1369    element Contact_Address {
1370    for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline
1371    return element Address {data($addressline)},
1372    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then
1373    element City {string($DataCuratorRole/moles:contactDetails/moles:address/moles:city)}
1374    else (),
1375    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)) then
1376    element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)}
1377    else (),
1378    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:country)) then
1379    element Country {string($DataCuratorRole/moles:contactDetails/moles:address/moles:country)}
1380    else ()
1381    }
1382    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address)) then
1383    element Contact_Address {
1384    for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline
1385    return element Address {data($addressline)},
1386    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then
1387    element City {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)}
1388    else (),
1389    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then
1390    element Postal_Code {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)}
1391    else (),
1392    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)) then
1393    element Country {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)}
1394    else ()
1395    }
1396    else ()
1397    }
1398    },
1399    element Summary {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},
1400    for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule
1401        return
1402            if ($DG/moles:dataModelID/moles:schemeIdentifier='NDG-A0') then
1403                       (element Related_URL {
1404                               element URL_Content_Type {'NDG_A_SERVICE'},
1405                               if (exists($DG/instance/URI)) then
1406                                   element URL {escape-uri($DG/instance/URI, true())}
1407                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1408                                   element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())}
1409                               else ($DG/moles:dataModelID/moles:repositoryIdentifier),
1410                             element Description {'The NDG service delivering data via NDG A metadata.'}
1411                           },
1412                      element Related_URL {
1413                               element URL_Content_Type {'GET DATA > CSML'},
1414                               if (exists($DG/instance)) then
1415                                   element URL {escape-uri($DG/instance/URI, true())}
1416                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1417                                   element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())}
1418                               else (),
1419                             element Description {'The NDG service delivering data via NDG A metadata. Additional tag to be more in line with latest version of GCMD valids'}
1420                           })
1421            else if ($DG/moles:dataModelID/moles:schemeIdentifier='CDML-0') then
1422                           (element Related_URL {
1423                                   element URL_Content_Type {'NDG_A_SERVICE'},
1424                               if (exists($DG/instance)) then
1425                                   element URL {escape-uri($DG/instance/URI, true())}
1426                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1427                                   element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())}
1428                               else (),
1429                             element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}
1430                               },
1431                           element Related_URL {
1432                               element URL_Content_Type {'GET DATA > DX'},
1433                               if (exists($DG/instance)) then
1434                                   element URL {escape-uri($DG/instance/URI, true())}
1435                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1436                                   element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())}
1437                               else (),
1438                             element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}
1439                               })
1440            else if ($DG/moles:dataModelID/moles:schemeIdentifier='URI') then
1441                       element Related_URL {
1442                             element URL {data($DG/moles:instance/moles:URI)},
1443                             if (exists($DG/moles:instance/moles:instanceComment)) then
1444                                     element Description {data($DG/moles:instance/moles:instanceComment)}           
1445                             else
1446                                     element Description {'URL to aid in delivering data. Note that this may point directly to the data or, more likely, point to the web site of the curator.'}
1447                          }
1448        else (),
1449        for $RelURL_Desc in ($DE/moles:dgMetadataDescription/moles:descriptionSection/moles:descriptionOnlineReference)
1450        return
1451                       if (exists($RelURL_Desc/moles:dgSimpleLink)) then
1452                       element Related_URL {
1453                       element URL {data($RelURL_Desc/moles:dgSimpleLink/URI)},
1454                       element Description {concat(data($RelURL_Desc/dgSimpleLink/moles:name), ' - ', data($RelURL_Desc/dgSimpleLink/moles:notes))}
1455                       }
1456                       else (),
1457    element Metadata_Name {'[CEOS IDN DIF]'},
1458    element Metadata_Version {'9.4'},
1459    if  (exists($DE/moles:dgMetadataProvenance/moles:RecordCreation)) then
1460            element DIF_Creation_Date {data($DE/moles:dgMetadataProvenance/moles:RecordCreation/moles:CreatedDate)}
1461    else (),
1462    for $MDUpdt in $DE/moles:dgMetadataProvenance/moles:RecordUpdate
1463    return 
1464        element DIF_Revision_History {concat(data($MDUpdt/moles:UpdateDate), ' - ', data($MDUpdt/moles:UpdateSummary), ' - ', data($MDUpdt/moles:UpdatedBy))},
1465    if  (exists($DE/moles:dgMetadataProvenance/moles:RecordReview)) then
1466            element Future_DIF_Review_Date {data($DE/moles:dgMetadataProvenance/moles:RecordReview/moles:ReviewDate)}
1467    else ()
1468        }
1469'''
1470       
1471DublinCoreDEQuery='''
1472import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1473import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1474declare default element namespace 'http://ndg.nerc.ac.uk/moles';
1475declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1476declare namespace dc='http://purl.org/dc/elements/1.1/';
1477declare namespace oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc/';
1478(:
1479declare variable $targetCollection as xs:string {'/db/ndg_B_metadata'};
1480declare variable $repositoryIdentifier as xs:string {'badc.nerc.ac.uk'};
1481declare variable $localIdentifier as xs:string {'dataent_chablis'};
1482:)
1483
1484declare variable $targetCollection as xs:string {'TargetCollection'};
1485declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1486declare variable $localIdentifier as xs:string {'LocalID'};
1487
1488for $DE in collection($targetCollection)/dgMetadata/dgMetadataRecord[
1489exists('dgDataEntity')
1490and dgMetadataID/repositoryIdentifier=$repositoryIdentifier
1491and dgMetadataID/localIdentifier=$localIdentifier]
1492return
1493element oai_dc:dc {
1494    attribute xsi:schemaLocation {'http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd'},
1495    element dc:title {string($DE/name)},
1496    element dc:type {'Dataset'},
1497    element dc:identifier {concat($DE/dgMetadataID/repositoryIdentifier, $utillib:moles_id_separator, 'DC', $utillib:moles_id_separator, $DE/dgMetadataID/localIdentifier)},
1498    for $identifiers in $DE/(dgMetadataDescription/descriptionSection/descriptionOnlineReference | abstract/abstractOnlineReference)[
1499        exists(dgReferenceClass/dgValidTermID/ParentListID)
1500        and
1501        voclib:spot-vocab($voclib:ndg_online_reference_classes_vocab, dgReferenceClass/dgValidTermID/ParentListID)
1502        and
1503        dgReferenceClass/dgValidTerm='DataPage']
1504    return element dc:identifier {data($identifiers/dgSimpleLink/URI)},
1505    element dc:description {string($DE/dgMetadataDescription/abstract/abstractText)},
1506    element dc:date
1507        {
1508        if (exists($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)) then
1509            for $updatedate in ($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)
1510                order by xs:date($updatedate)
1511            return data($updatedate[1])
1512        else
1513            string($DE/(dgMetadataProvenance | DataProvenance)/RecordCreation/CreatedDate)
1514        },
1515    for $StructuredKeyword in distinct-values($DE/dgStructuredKeyword[
1516    voclib:spot-vocab($voclib:cf_standard_names, dgValidTermID/ParentListID)
1517    or voclib:spot-vocab($voclib:gcmd_science_valids, dgValidTermID/ParentListID)
1518    or voclib:spot-vocab($voclib:gcmd_project_valids, dgValidTermID/ParentListID)
1519    or voclib:spot-vocab($voclib:iso_topic_list, dgValidTermID/ParentListID)
1520    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, dgValidTermID/ParentListID)
1521    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, dgValidTermID/ParentListID)
1522    ]/dgValidTerm)
1523    order by $StructuredKeyword
1524    return
1525        element dc:subject {string($StructuredKeyword)},
1526   
1527    for $StructuredKeyword1 in distinct-values($DE/dgDataEntity/dgDataSummary/dgParameterSummary/dgStdParameterMeasured[
1528    voclib:spot-vocab($voclib:gcmd_science_valids, dgValidTermID/ParentListID)
1529    or voclib:spot-vocab($voclib:gcmd_project_valids, dgValidTermID/ParentListID)
1530    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, dgValidTermID/ParentListID)
1531    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, dgValidTermID/ParentListID)
1532    ]/dgValidTerm)
1533        order by $StructuredKeyword1
1534    return
1535        element dc:subject  {string($StructuredKeyword1)},
1536    for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder
1537        order by $DataCreatorRole/startDate empty least
1538    return
1539        for $DataCreatorRoleHolder in collection($targetCollection)/dgMetadata/(dgOrganisation | dgPerson)
1540            [(dgMetadataID/schemeIdentifier='NDG-B0'
1541            and dgMetadataID/repositoryIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier
1542            and dgMetadataID/localIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/localIdentifier)]
1543        return
1544            element dc:creator {
1545                if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then
1546                    (string($DataCreatorRoleHolder/name))
1547                else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then
1548                    (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName))))
1549                else ('empty content')
1550            },
1551    for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate='']
1552        order by $DataCuratorRole/startDate empty least
1553    return
1554        for $DataCuratorRoleHolder in collection($targetCollection)/dgMetadata/(dgOrganisation | dgPerson)
1555            [(dgMetadataID/schemeIdentifier='NDG-B0'
1556            and dgMetadataID/repositoryIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier
1557            and dgMetadataID/localIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/localIdentifier)]
1558        return
1559            element dc:publisher {
1560                if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then
1561                    (string($DataCuratorRoleHolder/name))
1562                else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then
1563                    (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName))))
1564                else ('empty content')
1565}
1566}  (: </oai_dc:dc> :)
1567'''
1568
1569MDIPQuery='''import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1570import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1571declare default element namespace 'http://www.oceannet.org/mdip/xml';
1572declare namespace moles='http://ndg.nerc.ac.uk/moles';
1573declare namespace gco='http://www.isotc211.org/2005/gco';
1574declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1575declare variable $targetCollection as xs:string {'TargetCollection'};
1576declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1577declare variable $localIdentifier as xs:string {'LocalID'};
1578declare variable $ISO_639-2_ns as xs:string{$voclib:ISO_639-2_ns};
1579declare variable $ISO_3166_ns as xs:string{$voclib:ISO_3166_ns};
1580
1581for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
1582    exists('moles:dgDataEntity')
1583    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1584    and moles:dgMetadataID/moles:repositoryIdentifier=$repositoryIdentifier
1585    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
1586return
1587element Metadata {
1588    element Title {data($DE/moles:name)},
1589    if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage)) then
1590        for $lang in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage
1591        return
1592            element Language{
1593                element LanguageName {data($lang/moles:dgValidTerm)},
1594                element LanguageVocab {data($lang/moles:dgValidTermID/moles:ParentListID)},
1595                element LanguageCode {data($lang/moles:dgValidTermID/moles:TermID)}
1596            }
1597               
1598    else (),
1599
1600    element Abstract {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},
1601    for $isoTopic in $DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)]
1602    return element TopicCategory {
1603    element TopicCategoryName {data($isoTopic/moles:dgValidTerm)},
1604    element TopicCategoryVocab {data($isoTopic/moles:dgValidTermID/moles:ParentListID)},
1605    element TopicCategoryCode {data($isoTopic/moles:dgValidTermID/moles:TermID)}
1606    },
1607    for $subject in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured[
1608    voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID)
1609    or voclib:spot-vocab($voclib:gcmd_project_valids, moles:dgValidTermID/moles:ParentListID)
1610    or voclib:spot-vocab($voclib:gcmd_science_valids_categories, moles:dgValidTermID/moles:ParentListID)
1611    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, moles:dgValidTermID/moles:ParentListID)
1612    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, moles:dgValidTermID/moles:ParentListID)
1613    ])
1614    return (element Subject {
1615    element SubjectName {data($subject/moles:dgValidTerm)},
1616    element SubjectVocab {data($subject/moles:dgValidTermID/moles:ParentListID)},
1617    element SubjectCode {data($subject/moles:dgValidTermID/moles:TermID)}
1618    },
1619    for $subterm in $subject//moles:dgValidSubterm
1620    return (element Subject {
1621    element SubjectName {data($subterm/moles:dgValidTerm)},
1622    element SubjectVocab {data($subterm/moles:dgValidTermID/moles:ParentListID)},
1623    element SubjectCode {data($subterm/moles:dgValidTermID/moles:TermID)}
1624    }
1625    )
1626    ),
1627    if (exists($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange))) then
1628    element Date {
1629        element DatasetStartDate {
1630        let $dateStart:=min($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange/moles:DateRangeStart) cast as xs:date)
1631        return
1632        if (empty($dateStart)) then ()
1633        else data($dateStart)
1634        },
1635        element DatasetEndDate {
1636        let $dateEnd:=max($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange/moles:DateRangeEnd) cast as xs:date)
1637        return
1638        if (empty($dateEnd)) then ()
1639        else data($dateEnd)
1640        }
1641    }
1642    else (),
1643    let $west := min($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitWest cast as xs:decimal)
1644    return element WestCoOrdinate {data($west)},
1645    let $east := max($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitEast cast as xs:decimal)
1646    return element EastCoOrdinate {data($east)},
1647    let $north := max($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitNorth cast as xs:decimal)
1648    return element NorthCoOrdinate {data($north)},
1649    let $south := min($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitSouth cast as xs:decimal)
1650    return element SouthCoOrdinate {data($south)},
1651    element DatasetIdentifier {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'MDIP', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)},
1652    for $target in $DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:ndg_data_provider_vocab, moles:dgValidTermID/moles:ParentListID) ]
1653    return element Target {
1654    element TargetName {data($target/moles:dgValidTerm)},
1655    element TargetVocab {data($target/moles:dgValidTermID/moles:ParentListID)},
1656    element TargetCode {data($target/moles:dgValidTermID/moles:TermID)}
1657    }
1658    }
1659'''
Note: See TracBrowser for help on using the repository browser.