Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.misc -> Re: How to Generate XML and call a query on it?
I have recently started looking into XML in the database, and was
amazed (and confused) by the range of options. There are a set of
queries called SQLX queries that will do what you want (couple with the
build in type for xml XMLTYPE). I will try to post an example that
does what you want, and then you will have to look in the XML
Developers Guide for the details.
create table testxml (regionnum varchar2(10),
regionname varchar2(10),
people varchar2(50) );
insert into testxml values ('reg1','place a','A Person'); insert into testxml values ('reg2','place b','B Person');
select
XMLELEMENT( "RegionNum", regionnum ), XMLELEMENT( "RegionName", regionname ), XMLELEMENT( "Person", people )from
XMLELEMENT("REGIONNUM",REGIONNUM)
<RegionNum>reg2</RegionNum>
<RegionName>place b</RegionName>
<Person>B Person</Person>
So the SQLX function xmlelement produces tags with your desired tag
name, and a value of you choice.
To add the regions 'wrapper' tag use this query:
select XMLELEMENT ( "REGION",
XMLELEMENT( "RegionNum", regionnum ), XMLELEMENT( "RegionName", regionname ), XMLELEMENT( "Person", people ) )from
XMLELEMENT("REGION",XMLELEMENT("REGIONNUM",REGIONNUM),XMLELEMENT("REGIONNAME",RE
Now, to add a wrapper <REGIONS> around all the rows of the set use the XMLAGG function which is kind of like group by, as it returns all rows aggrigated:-
SQL> select XMLELEMENT ( "REGIONS",
2 XMLAGG ( XMLELEMENT ( "REGION", 3 XMLELEMENT( "RegionNum", regionnum ), 4 XMLELEMENT( "RegionName", regionname ), 5 XMLELEMENT( "Person", people ) ) 6 ) ) 7
XMLELEMENT("REGIONS",XMLAGG(XMLELEMENT("REGION",XMLELEMENT("REGIONNUM",REGIONNUM
SQL> So that gets you the XML you want, and in PLSQL it returns it as an XMLTYPE variable, meaning you can use the XML query functions on it existsnode, getstringval, etc that take XPath expressions, however why do you want to generate XML and then filter it this way? Surely you query should filter out the rows you dont want and just return the xml as you want it:
select XMLELEMENT ( "REGIONS",
XMLAGG ( XMLELEMENT ( "REGION", XMLELEMENT( "RegionNum", regionnum ), XMLELEMENT( "RegionName", regionname ), XMLELEMENT( "Person", people ) ) ) )