How to change the structure of XML using XQuery

I have an XML file called Employees Name and Job, executed by them. XML file structure -

<Employee>AAA@A#B#C#D</Employee>
<Employee>BBB@A#B#C#D</Employee>
<Employee>CCC@A#B#C#D</Employee>
<Employee>DDD@A#B#C#D</Employee>

There are thousands of records, and I need to change the structure to

<Employee>
  <Name>AAA</Name>
  <Jobs>
   <Job>A</Job>
   <Job>B</Job>
   <Job>C</Job>
   <Job>D</Job>
  </Jobs>
</Employee>

How to do this using XQuery in BaseX?

+4
source share
2 answers

3 functions XQuery, substring-before, substring-afterand tokenizeare used to obtain the desired output.

substring-before used to get the name.

Similarly, it is substring-afterused to receive a task.

The function tokenizeis then used to separate tasks.

let $data :=
  <E>
    <Employee>AAA@A#B#C#D</Employee>
    <Employee>BBB@A#B#C#D</Employee>
    <Employee>CCC@A#B#C#D</Employee>
    <Employee>DDD@A#B#C#D</Employee>
  </E>


for $x in $data/Employee
return 

<Employee>
   {<Name>{substring-before($x,"@")}</Name>}
   {<Jobs>{
   for $tag in tokenize(substring-after($x,"@"),'#')
   return 
     <Job>{$tag}</Job>
   }</Jobs>
}</Employee>

NTN ...

+4
source

, , . tokenize($string, $pattern) $string, $pattern, head($seq) tail($seq) , . , , .

for $employee in //Employee
let $tokens := tokenize($employee, '[@#]')
return element Employee {
  element Name { head($tokens) },
  element Jobs {
    for $job in tail($tokens)
    return element Job { $job }
  }
}
+2

All Articles