Search code examples
xmlcsvxquery

Interleave multiple values from two elements in parent element's context?


I have data like this:

<?xml version="1.0" encoding="UTF-8"?>
<colors>
   <color id="ff0000">
      <label language="en">red</label>
      <label language="de">rot</label>
      <label language="es">rojo</label>
   </color>
   <color id="008000">
      <label language="en">green</label>
      <label language="de">gruen</label>
      <label language="es">verde</label>
   </color>
   <color id="0000ff">
      <label language="en">blue</label>
      <label language="de">blau</label>
      <label language="es">azul</label>
   </color>
</colors>

I would like to convert it into a table like this

+--------+----------------------------+
| id     | labels                     |
+--------+----------------------------+
| ff0000 | en:red|de:rot|es:rojo      |
+--------+----------------------------+
| 008000 | en:green|de:gruen|es:verde |
+--------+----------------------------+
| 0000ff | en:blue|de:blau|es:azul    |
+--------+----------------------------+

I know how to join multiple values from the same parent element's context, but I don't know how to paste an attribute and data for one element, and then paste those combinations across the parent element.

declare option output:method "csv";
declare option output:csv "header=yes, separator=tab";

for $color in doc(
  'color_words'
)/colors/color

let $id := data($color/@id)
let $language := fn:normalize-space(string-join($color/label/@language,'|'))
let $label := fn:normalize-space(string-join($color/label,'|'))

return

<csv>
  <record>
    <id>
      {$id}
    </id>
    <language>
      {$language}
    </language>
    <label>
      {$label}
    </label>
  </record>
</csv>
+--------+----------+-------------------+
| id     | language | label             |
+--------+----------+-------------------+
| ff0000 | en|de|es | red|rot|rojo      |
+--------+----------+-------------------+
| 008000 | en|de|es | green|gruen|verde |
+--------+----------+-------------------+
| 0000ff | en|de|es | blue|blau|azul    |
+--------+----------+-------------------+

Solution

  • You can use this let-expression:

    let $label := fn:normalize-space(string-join($color/label/concat(@language,':',.),'|'))
    

    It will create the output desired. The other let-expression is not necessary.