declare function local:getRelated20s($item) { let $nextItem :=$item/following-sibling::*[local-name()!="record_20"and local-name()!="record_30"][1] for $related in $item/following-sibling::*[local-name()="record_20"] where if ($nextItem) then $related << $nextItem else true() return $related }; declare function local:getRelated30s($item) { let $nextItem := $item/following-sibling::*[local-name()!="record_30"][1] for $related in $item/following-sibling::*[local-name()="record_30"] where if($nextItem) then $related << $nextItem else true() return $related }; declare function local:getRelated11($item) { let $nextItem := $item/following-sibling::*[local-name()!="record_10"][1] for $related in $item/following-sibling::*[local-name()="record_11"] where if($nextItem) then $related << $nextItem else true() return $related }; <DataSets> { for $record_10 in doc('G:/Projects/knowledge/proprietaryInputFile_trailer.xml')/root/record_10 return <DataSet> <CustomerId> {$record_10/customer_id/text()} </CustomerId> <CustomerName> {$record_10/lastname/text()} </CustomerName> <CustomerFirstName> {$record_10/firstname/text()} </CustomerFirstName> <Accounts> { for $record_20 in local:getRelated20s($record_10) return <Account> <AccountId> {$record_20/account_id/text()} </AccountId> <Transactions> { for $record_30 in local:getRelated30s($record_20) return <Transaction> <Label>{$record_30/label/text()}</Label> <Value>{$record_30/value/text()}</Value> </Transaction> } </Transactions> </Account> } </Accounts> { for $record11 in local:getRelated11($record_10) return <total_20>{$record11/total_20/text()}</total_20> } </DataSet> } </DataSets> (: Stylus Studio meta-information - (c) 2004-2007. Progress Software Corporation. All rights reserved. <metaInformation> <scenarios ><scenario default="yes" name="Scenario1" userelativepaths="yes" externalpreview="no" useresolver="yes" url="" outputurl="" processortype="datadirect" tcpport="0" profilemode="0" profiledepth="" profilelength="" urlprofilexml="" commandline="" additionalpath="" additionalclasspath="" postprocessortype="none" postprocesscommandline="" postprocessadditionalpath="" postprocessgeneratedext="" host="" port="0" user="" password="" validateoutput="no" validator="internal" customvalidator=""/></scenarios><MapperMetaTag><MapperInfo srcSchemaPathIsRelative="yes" srcSchemaInterpretAsXML="no" destSchemaPath="" destSchemaRoot="" destSchemaPathIsRelative="yes" destSchemaInterpretAsXML="no"/><MapperBlockPosition></MapperBlockPosition><TemplateContext></TemplateContext><MapperFilter side="source"></MapperFilter></MapperMetaTag> </metaInformation> :)