Return multiple XML nodes and Custom parent tag using FLWOR XQuery

瘦欲@ 提交于 2019-12-11 17:08:21

问题


I need to get the following output using a FLWOR expression.

<oldPlanes>
  <make>Cessna</make>
  <model>Centurian</model>
  <make>Piper</make>
  <model>Tripacer</model>
</oldPlanes>

using

CREATE TABLE XMLO1 (xDoc XML NOT NULL)

INSERT INTO XMLO1 VALUES ('
 <planes>
   <plane>
     <year>1977</year>
     <make>Cessna</make>
     <model>Skyhawk</model>
     <color>Light blue and white</color>
   </plane>
   <plane>
     <year>1975</year>
     <make>Piper</make>
     <model>Apache</model>
     <color>White</color>
   </plane>
   <plane>
     <year>1960</year>
     <make>Cessna</make>
     <model>Senturian</model>
     <color>Yellow and White</color>
   </plane>
   <plane>
     <year>1956</year>
     <make>Piper</make>
     <model>ripacer</model>
     <color>Blue</color>
   </plane>
 </planes>')

I tried the below query

SELECT xDoc.query('for $p in //plane
                    let $x:=$p/year
                    where $x < 1970
                    return <oldPlanes><make>{data($p/make)}</make> 
                           </oldPlanes>
                    ')
FROM XMLO1

This doesn't gives me the expected output to find the planes where Year < 1970.

How to set a custom parent node as <oldPlanes>

How to return 2 nodes as the expected output?


回答1:


You only want to create one oldPlanes element so its construction needs to be outside the FLWOR expression:

<oldPlanes>{for $p in //plane
            let $x:=$p/year
            where $x < 1970
            return $p/(make, model)}</oldPlanes>

Except that you don't need a FLWOR for this at all, a simple path expression will do the job:

<oldPlanes>{//plane[year < 1970]/(make, model)}</oldPlanes>


来源:https://stackoverflow.com/questions/56802601/return-multiple-xml-nodes-and-custom-parent-tag-using-flwor-xquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!