Reputation: 115
I have a XML file which contains multiple XML documents. In large XML document each document has a root node and it is common for all the XML documents in that file. However the child elements inside the root name vary. I have to write a for loop to iterate dynamically each and every child node and have to show it on a table format. Here I have pasted my XML format below. I have multiple xml files in that way but the root node is common for every file. I want to map each child element as table row and data as table column. child elements numbers would vary
<source>
<empname>john </empname>
<empid>25825 </empid>
<salary> 20000 </salary>
<dob> 12-08-1993</dob>
</source>
<source>
<empname>joe</empname>
<empid>25826</empid>
<salary>20000</salary>
<dob>12-07-1993</dob>
<source>
<source>
<emptype>developer</emptype>
<address>3155 </address>
<mobile>58258365</mobile>
</source>
<source>
<emptype>analyst</emptype>
<address>3155 </address>
<mobile>58258365</mobile>
</source>
<table>
<th> empname empid salary dob </th>
<td> john 25825 60000 date</td>
<td> joe 25826 70000 date</td>
</table>
Every time the <th>
and <td>
is changed and the common thing is root element source code. Can anyone help me out to iterate those elements over loop and represent those data over table format?
Upvotes: 0
Views: 5268
Reputation: 20414
You could try this, but the approach of distinct-values doesn't scale well. You best determine the columns upfront, and hardcode like the solution from Tavolo:
let $xml :=
<sources>
<source>
<empname>john </empname>
<empid>25825 </empid>
<salary> 20000 </salary>
<dob> 12-08-1993</dob>
</source>
<source>
<empname>joe</empname>
<empid>25826</empid>
<salary>20000</salary>
<dob>12-07-1993</dob>
</source>
<source>
<emptype>developer</emptype>
<address>3155 </address>
<mobile>58258365</mobile>
</source>
<source>
<emptype>analyst</emptype>
<address>3155 </address>
<mobile>58258365</mobile>
</source>
</sources>
let $sources := $xml/source
let $labels := fn:distinct-values($sources/*/fn:node-name(.))
return
<table>
<tr>{
for $label in $labels
return <th>{ $label }</th>
}</tr>
{
for $source in $sources
return <tr>{
for $label in $labels
return <th>{ fn:data($source/*[fn:node-name() = $label]) }</th>
}</tr>
}
</table>
HTH!
Upvotes: 1
Reputation: 579
I do not fully understand your statement. Do you want to be able to combine all such XML files? How about this?
<table>
<tr><th>empname</th><th>empid</th><th>salary</th><th>dob</th> <th>emptype</th></tr>
{for $child in doc("your-file")/source)
return <tr>{
return <td>{$child/empname}</td><td>{$child/empid}</td><td>{$child/salary}</td><td>{$child/dob}</td><td>{$child/emptype}</td>
}</tr></table>
Upvotes: 1