How to return data from multiple XML nodes using Xquery with a namespace?

58 views Asked by At

Using the Microsoft namespace as below, how to return output like:

<first>a</first>
<last>b</last>
<first>c</first>
<last>c</last>

Where I'm running into a syntax error with the return clause:

nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ basex sample.xq 
Stopped at /home/nicholas/flwor/sample.xq, 17/37:
[XPST0003] Expecting ')', found '>'.
nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ basex sample.full.xq 
<Objs xmlns="http://schemas.microsoft.com/powershell/2004/04" Version="1.1.0.1">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="First Name">a</S>
      <S N="Last Name">b</S>
      <S N="Emails">a@b;[email protected]</S>
      <S N="Phones">123 456-8904</S>
      <S N="Company Name"/>
    </MS>
  </Obj>
  <Obj RefId="1">
    <TNRef RefId="0"/>
    <MS>
      <S N="First Name">c</S>
      <S N="Last Name">c</S>
      <S N="Emails">[email protected]</S>
      <S N="Phones">123456-3532;563 346-3453</S>
      <S N="Company Name"/>
    </MS>
  </Obj>
</Objs>nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ cat sample.xq 

xquery version "3.1";


declare namespace ns1="http://schemas.microsoft.com/powershell/2004/04";


for $contact in db:open("sample")


let $first  := $contact//ns1:S[1][@N="First Name"]/data() 
let $last   := $contact//ns1:S[2][@N="Last Name"]/data() 
let $emails := $contact//ns1:S[3][@N="Emails"]/data() 
let $phones := $contact//ns1:S[4][@N="Phones"]/data() 


return (<first>{$first}</first><last>{$last}</last>)

nicholas@mordor:~/flwor$ 

I've tried a few ways of wrapping the return clause with parenthesis or curly brackets, but the examples I've seen aren't using a namespace as here.

the example output isn't distinguishing one contact from another.

1

There are 1 answers

0
Jack Fleeting On

Try it this way

for $contact in db:open("sample")//*:MS
let $first := $contact//*:S[@N="First Name"]/text(),
  $last:= $contact//*:S[@N="Last Name"]/text()
return (<first>{$first}</first>,<last>{$last}</last>)

Output should be

<first>a</first>
<last>b</last>
<first>c</first>
<last>c</last>