0

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()

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. $document/garage/car/element() did the trick. Never thought about it before. Thas a lot @dirkk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.