Nicholas Saunders
Nicholas Saunders

Reputation: 764

How to include element tags within the return results for an XQuery FLWOR?

How do I mix "new" tags in the return clause for an xquery?

this is the form of the output I'm after:

<?xml version="1.0"?>
<csv>
  <record>
    <sex>M</sex>
  </record>
  <record>
    <sex>F</sex>
  </record>
  <record>
    <sex>M</sex>
  </record>
  <record>
    <sex>F</sex>
  </record>
</csv>

The specific values I just entered by hand for illustration purposes. Actual values, and current output, is:

<?xml version="1.0" encoding="UTF-8"?><csv>SexMFFMFFMF</csv>

original xml data:

<csv>
  <record>
    <entry>Reported_Date</entry>
    <entry>HA</entry>
    <entry>Sex</entry>
    <entry>Age_Group</entry>
    <entry>Classification_Reported</entry>
  </record>
  <record>
    <entry>2020-01-26</entry>
    <entry>Vancouver Coastal</entry>
    <entry>M</entry>
    <entry>40-49</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-02</entry>
    <entry>Vancouver Coastal</entry>
    <entry>F</entry>
    <entry>50-59</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-05</entry>
    <entry>Vancouver Coastal</entry>
    <entry>F</entry>
    <entry>20-29</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-05</entry>
    <entry>Vancouver Coastal</entry>
    <entry>M</entry>
    <entry>30-39</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-11</entry>
    <entry>Interior</entry>
    <entry>F</entry>
    <entry>30-39</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-20</entry>
    <entry>Fraser</entry>
    <entry>F</entry>
    <entry>30-39</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-21</entry>
    <entry>Fraser</entry>
    <entry>M</entry>
    <entry>40-49</entry>
    <entry>Lab-diagnosed</entry>
  </record>
  <record>
    <entry>2020-02-27</entry>
    <entry>Vancouver Coastal</entry>
    <entry>F</entry>
    <entry>60-69</entry>
    <entry>Lab-diagnosed</entry>
  </record>
</csv>

The FLWOR query:

declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

for $x in /csv

return <csv>{$x/record[position() = (1 to 9)]/entry[3]/text()}</csv>

I've tried putting node tags within the curly braces but run into syntax errors.

Upvotes: 0

Views: 207

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

Use e.g.

<csv>
{
for $record in /csv/record[position() = (2 to 9)]
return
  <record>
    <sex>{data($record/entry[3])}</sex>
  </record>
}
</csv>

or the simple map operator

<csv>
{
  /csv/record[position() = (2 to 9)]
  !
  <record>
    <sex>{data(entry[3])}</sex>
  </record>
}
</csv>

Upvotes: 1

Related Questions