⌘BABAKOV.NET Let's code!
100% [dark] [ru]

XML in Oracle PL/SQL (Part 2 - Retrieving data as XML)

In the previous publication, some methods of manipulating XML in Oracle were considered, now let's consider how to retrieve data directly in XML. This is, in my opinion, the most interesting part.

In practice, it turned out that for Oracle in most cases it does not matter whether to return a set of records or a formed ready XML of this set of records - in terms of execution time these actions are subjectively almost equivalent. But if you have a need to form some XML structure in the application based on data received from the Oracle database, it will almost certainly be a resource-intensive event, much easier to transfer this functionality to the database, although at first glance it seems that this is not what the database engine should do.
Let's start.
For experiments with queries, we will need a couple of tables, with which we will conduct experiments.

Create a table with cities:

create table CITY
(
  id   NUMBER not null, -- Идентификатор города
  name NVARCHAR2(100) not null -- Наименование города
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );



Create a table with streets:

create table STREET
(
  id      NUMBER not null, -- Идентификатор улицы
  id_city NUMBER not null, -- Идентификатор города
  name    NVARCHAR2(100) not null -- Наименование улицы
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );



Fill our tables with demonstration data:

--Добавляем города
insert into CITY (ID, NAME) values (1, \'Красноярск\');
insert into CITY (ID, NAME) values (2, \'Москва\');
insert into CITY (ID, NAME) values (3, \'Новосибирск\');
commit;

--Добавляем улицы
insert into STREET (ID, ID_CITY, NAME) values (1, 1, \'Мира\');
insert into STREET (ID, ID_CITY, NAME) values (2, 1, \'Ленина\');
insert into STREET (ID, ID_CITY, NAME) values (3, 2, \'Кутузова\');
insert into STREET (ID, ID_CITY, NAME) values (4, 2, \'Ломоносова\');
insert into STREET (ID, ID_CITY, NAME) values (5, 3, \'Чернышевского\');
insert into STREET (ID, ID_CITY, NAME) values (6, 3, \'Карамзина\');



Now everything is ready, let's get started.

1. XMLElement - XML node selection

In the simplest form, a query in the form of XML looks like this:

select XMLElement("city",\'Moscow\') from dual;



Result:

<city>Moscow</city>



Now let's do the same with our CITY table - select all cities.

select XMLELEMENT("city",c.name) from city c;



Result:

<city>Красноярск</city>
<city>Москва</city>
<city>Новосибирск</city>



As a result, we got a set of elements, now let's learn how to combine all these elements into one parent node, it's easy.

2. XMLAGG - Combining (grouping) elements into a parent node.

Combine all our cities from the previous example into one parent node country.

select XMLELEment("country",XMLAGG(XMLELEMENT("city",c.name))) from city c;



Result:

<country>
	<city>Красноярск</city>
	<city>Москва</city>
	<city>Новосибирск</city>
</country>



As we can see, as a result, we got an element country with a nested set of elements city.

Now let's add the country name, and learn how to add attributes.

3. XMLATTRIBUTES - Adding attributes to an XML element.

Let's start with the simple - add the country name.
For this, you just need to add another parameter XMLATTRIBUTES with the listed attributes in parentheses after the node name.

select XMLELEment("country",xmlattributes(\'Россия\' as "name"),XMLAGG(XMLELEMENT("city",c.name))) from city c;



Result:

<country name="Россия">
	<city>Красноярск</city>
	<city>Москва</city>
	<city>Новосибирск</city>
</country>



That's all we need to know about retrieving data in the form of XML, now let's try to do something more complex.

First, let's move the city name to an attribute, and add the city identifier.

select XMLELEment("country",xmlattributes(\'Россия\' as "name"),
       XMLAGG(XMLELEMENT("city",
       xmlattributes(c.id as "id", c.name as "name")))) from city c;



As a result, we will get an XML of the following type:

<country name="Россия">
	<city id="1" name="Красноярск"></city>
	<city id="2" name="Москва"></city>
	<city id="3" name="Новосибирск"></city>
</country>



Now let's add child elements to the cities - streets.
We will need to use grouping.
Attach the street table and group by identifier and city name.

select XMLELEment("country",xmlattributes(\'Россия\' as "name"),
       XMLAGG(XMLELEMENT("city",
       xmlattributes(c.id as "id", c.name as "name"),
       XMLAGG(XMLELEMENT("street",
       xmlattributes(s.id as "id", s.name as "name")))
       )))
        from city c 
             left join street s on s.id_city=c.id
             group by c.id, c.name;



As a result, we will get an XML of the following type:

<country name="Россия">
	<city id="1" name="Красноярск">
		<street id="1" name="Мира"></street>
		<street id="2" name="Ленина"></street>
	</city>
	<city id="2" name="Москва">
		<street id="3" name="Кутузова"></street>
		<street id="4" name="Ломоносова"></street>
	</city>
	<city id="3" name="Новосибирск">
		<street id="5" name="Чернышевского"></street>
		<street id="6" name="Карамзина"></street>
	</city>
</country>



This is probably the main thing that needs to be known.
Further, you can develop and combine different constructions to get, in principle, any XML.

That's it, comments and questions are welcome.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.