loveMeansNothing
loveMeansNothing

Reputation: 361

for loop not returning what i expected

this is the xml document, let's call it document.xml for the sake of the example

<garage>
   <bike>
       <brand>Ducati</brand>
       <year>2000</year>
   </bike>
   <bike>
       <brand>Honda</brand>
       <year>2008</year>
   </bike>
   <bicycle>
       <brand>Trek</brand>
       <year>2004</year>
   </bicycle>
   <car>
       <brand>Porsche</brand>
       <year>1987</year>
   </car>
   <car>
       <brand>Volvo</brand>
       <year>2008</year>
   </car>
   <car>
       <brand>Ford</brand>
       <year>2012</year>
   </car>
</garage>

I want to retrieve this, which is all the car elements

      <car>
        <brand>Porsche</brand>
        <year>1987</year>
      </car>
      <car>
        <brand>Volvo</brand>
        <year>2008</year>
      </car>
      <car>
        <brand>Ford</brand>
        <year>2012</year>
      </car>

This is my xquery file:

     let $document:=doc('document.xml')

     for $car in $document/garage[descendant::car]
     return
     <car>
        <brand>{$car/brand/text()}</brand>
        <year>{$car/year/text()}</year>
     </car>

Instead, with this xquery file, i'm getting this:

    <car>
       <brand>PorscheVolvoFord</brand>
       <year>198720082012</year>
    </car>

Also tried this:

     let $document:=doc('document.xml')
     let $i:=0

     for $car in $document/garage[descendant::car]
     let $i:=$i+1
     return
     <car>
        <brand>{$car[$i]/brand/text()}</brand>
        <year>{$car[$i]/year/text()}</year>
     </car>

but could only retrieve the index[1]:

   <car>
      <brand>Porsche</brand>
      <year>1987</year>
   </car>

EDIT:

SOLVED IT! Thanks to @dirkk

What worked for me was:

for $car in $document/garage[descendants::car]
return $car/element()

Upvotes: 0

Views: 29

Answers (1)

dirkk
dirkk

Reputation: 6218

I don't know what XQuery processor you are using, but the output you claim to get is incorrect for the given XQueries. $car is actually bound to a garage element, thus $car/brand will be an empty result. You have to do:

 for $car in $document/garage/car
 return
 <car>
    <brand>{$car/brand/string()}</brand>
    <year>{$car/year/string()}</year>
 </car>

If you want the whole car element, you can simply do:

$document/garage/car

Also, you should use string() instead of text(), it has several benefits (e.g. you do not get comments back, if there are any in your XML.

Upvotes: 1

Related Questions