'Looping through XML using XQuery

I am getting an XML response like below from a webserice:

<root>
   <_1>
      <nodeId>6163</nodeId>
      <tableName>Employee</tableName>
      <name>Mark</name>
      <description>this is a test</description>
      <id>100</id>
   </_1>
   <_2>
      <nodeId>700731c</nodeId>
      <tableName>Employee</tableName>
      <name>Will</name>
      <id>200</id>
   </_2>
   <_3>
      <nodeId>8000</nodeId>
      <tableName>Employee</tableName>
      <name>Jack</name>
      <id>300</id>
   </_3>
   <_4>
      <nodeId>a3458</nodeId>
      <tableName>Employee</tableName>
      <name>Nathan</name>
      <id>400</id>
   </_4>
</root>

Now I want to loop through this xml and get only name and id for each array element. The code I am using is:

for $r in //root
return
<employeeResponse>
   <name>{$r//name/text()}</name>
   <id>{$r//id/text()}</id>
</employeeResponse>

But it is giving me the output but not producing the output in following format:

<employeeResponse>
  <name>Mark</name>
  <id>100</id>
</employeeResponse>
<employeeResponse>
  <name>Will</name>
  <id>200</id>
</employeeResponse>
<employeeResponse>
  <name>Jack</name>
  <id>300</id>
</employeeResponse>
<employeeResponse>
  <name>Nathan</name>
  <id>400</id>
</employeeResponse>

What wrong am I doing here?



Solution 1:[1]

You can iterate over the children of root:

for $r in /root/*
return
<employeeResponse>
   <name>{$r//name/text()}</name>
   <id>{$r//id/text()}</id>
</employeeResponse>

Its output is as desired, except for indentation.

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 zx485