'How do I prevent duplication of my root xml during my for loop

for $i in doc(test.xml)//hosptial

return file:append(filepath\dirTest.xml,
    <studentID>
        <hospitalName>
            <ambo>{$i//ambo}</ambo>
        </hospitalName>
    <studentID>
)

my file executes successfully but because test.xml has multiple hospitals when it loops it recreates my studentID and makes my xml not wellformed



Solution 1:[1]

If I understand correctly, you want to have one root element studentID and potentially several hospitalName in it. So you need to take the root element out of the loop and simply embed the loop "inside" it:

<studentID> {
  for $i in doc(test.xml)//hosptial
  return
    <hospitalName>
      <ambo>{$i//ambo}</ambo>
    </hospitalName>
}
<studentID>

I removed the call to file:append, which I am not sure to understand here. But the above code would give you the element I think you want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Florent Georges