XQuery "flattening" an element

395 views Asked by At

I am extracting data from an XML file and I need to extract a delimited list of sub-elements. I have the following:

for $record in //record
let $person := $record/person/names
return concat($record/@uid/string()
  ,",", $record/@category/string()
  ,",", $person/first_name
  ,",", $person/last_name
  ,",", $record/details/citizenships
  ,"
")

The element "citizenships" contains sub-elements called "citizenship" and as the query stands it sticks them all together in one string, e.g. "UKFrance". I need to keep them in one string but separate them, e.g. "UK|France".

Thanks in advance for any help!

1

There are 1 answers

7
Charles Duffy On BEST ANSWER

fn:string-join($arg1 as xs:string*, $arg2 as xs:string) is what you're looking for here.

In your currently desired usage, that would look something like the following:

fn:string-join($record/details/citizenships/citizenship, "|")

Testing outside your document, with:

fn:string-join(("UK", "France"), "|")

...returns:

UK|France

Notably, ("UK", "France") is a sequence of strings, just as a query returning multiple citizenships would likewise be a sequence (the entries in which will be evaluated for their string value when passed to fn:string-join(), which is typed as taking a sequence of strings for its first argument).


Consider the following (simplified) query:

declare context item := document { <root>
  <record uid="1">
    <person>
      <citizenships>
        <citizenship>France</citizenship>
        <citizenship>UK</citizenship>
      </citizenships>
    </person>
  </record>
</root> };

for $record in //record
return concat(fn:string-join($record//citizenship, "|"), "&#10;")

...and its output:

France|UK