Question

I have an XML document with the following data. What I need to do is to display this. For every new plant an attribute called id should be added to display a sequential number. The first plant is 1, the second type of plant 2 and so on. I am not sure where to start...any guidance will be appreciated.

<CATALOG>
<PLANT>
<COMMON>ABC</COMMON>
<BOTANICAL>MNO</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Shady</LIGHT>
</PLANT>
<PLANT>
<COMMON>PQR</COMMON>
<BOTANICAL>FGH</BOTANICAL>
<ZONE>3</ZONE>
<LIGHT>Mostly Shady</LIGHT>
</PLANT>
</CATALOG>

Output should look like this :

<CATALOG>
<PLANT id="1">
<COMMON>ABC</COMMON>
<BOTANICAL>MNO</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Shady</LIGHT>
</PLANT>
<PLANT  id="2">
<COMMON>PQR</COMMON>
<BOTANICAL>FGH</BOTANICAL>
<ZONE>3</ZONE>
<LIGHT>Mostly Shady</LIGHT>
</PLANT>
</CATALOG>

Thanks for your help.

Was it helpful?

Solution

use a positional var in your flowr expression:

for $p at $id in //PLANT
return <PLANT id="{$id}">{$p/*}</PLANT>

OTHER TIPS

If you've got access to XQuery Update, you can also change the original document.

for $plant at $id in /CATALOG/PLANT
return insert node attribute id { $id } into $plant

Or use XQuery Update transformations, which only change a copy:

copy $result := /.
modify (
  for $plant at $id in $result/CATALOG/PLANT
  return insert node attribute id { $id } into $plant
)
return $result

This is more bulky than reconstructing the XML tree like @Ewout Graswinckel did, but will get handy if you want to change more details on different levels of the tree.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top