Nicholas Saunders
Nicholas Saunders

Reputation: 764

How to add a node attribute based on a nested index counter using FLWOR?

The following output isn't too far off, but the query's creating a new record element for each entry record whereas the original data has four entry element nodes in each record.

In this way, some data is being erased. There should be four entry nodes which are children of a record node, the record; the root element is csv.

How can I add attributes to each entry element without altering the document tree?

What I'm looking for is like:

<record>
<entry num="1">2020-01-26</entry>
<entry num="2">Vancouver Coastal</entry>
..
<record>
<entry num="1">2020-02-02</entry>
..

so that the "counter" restarts for each record.

current output:

<csv>
  <record>
    <entry num="1">2020-01-26</entry>
  </record>
  <record>
    <entry num="2">Vancouver Coastal</entry>
  </record>
  <record>
    <entry num="3">M</entry>
  </record>
  <record>
    <entry num="4">40-49</entry>
  </record>
  <record>
    <entry num="5">Lab-diagnosed</entry>
  </record>
  <record>
    <entry num="6">2020-02-02</entry>
  </record>
  <record>
    <entry num="7">Vancouver Coastal</entry>
  </record>
  <record>
    <entry num="8">baz</entry>
  </record>
  <record>
    <entry num="9">50-59</entry>
  </record>
  <record>
    <entry num="10">Lab-diagnosed</entry>
  </record>
  <record>
    <entry num="11">2020-02-05</entry>
  </record>
  <record>
    <entry num="12">Vancouver Coastal</entry>
  </record>
  <record>
    <entry num="13">F</entry>
  </record>
  <record>
    <entry num="14">20-29</entry>
  </record>
  <record>
    <entry num="15">Lab-diagnosed</entry>
  </record>
</csv>

xquery:

<csv>
{    

for $x at $i in db:open("bccdc_covid19.abbreviated")/csv/record/entry

return <record><entry num="{$i}">{$x/@*, $x/node()}</entry></record>

}


</csv>

input:

<csv>
  <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>baz</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>
</csv>

Looking to maintain the structure of the original document above.

Upvotes: 0

Views: 60

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

You can nest all such structures e.g.

<csv>
{
    for $record in csv/record
    return
        <record>
        {
            for $entry at $pos in $record/entry
            return
                <entry num="{$pos}">{data($entry)}</entry>
        }
        </record>
}
</csv>

Upvotes: 1

Related Questions