SlideShare a Scribd company logo
Generating XML Data from the Database
XML data can be generated by following methods.
 Generating XML Using Standard SQL/XML Functions.
 Generating XML Using Oracle Database SQL Functions.
 Generating XML Using DBMS_XMLGEN.
 Generating XML Using XSQL Pages Publishing Framework.
 Generating XML Using XML SQL Utility (XSU).
 Guidelines for Generating XML with Oracle XML DB.
1. Generation of XML Using Standard SQL/XML Functions.
i. XMLELEMENT:
 Used to construct XML instances from relational data.
 Takes element name as argument along with an optional collection of attributes for
the element.
Syntax: XMLElement(“TagName", column, [xmlAttributes])
Scenario1: To Generate xml containing individual element from a table.
select xmlelement("Empno",empno),xmlelement("EmpName",ename) from emp
where rownum<3;
Scenario2: To Generate an xml containing multiple elements from a table.
Select xmlelement( "EmpDetails" , xmlelement ("Empno",empno) ,
xmlelement("EmpName",ename)) from emp where rownum<3;
Scenario3:
To Generate a nested xml(Master Detail relationship) containing elements from two
tables.
Query:
select xmlroot(xmlelement("Department", xmlelement("DeptNo",d.deptno)
, xmlelement("DeptName",d.dname), xmlelement("Location",d.loc)
,(select xmlelement("Employees",
xmlagg(xmlelement("Employee",xmlelement("Empno",e.empno),xmlelement("EmpName"
,e.ename),xmlelement("Position",e.job))))
from emp e where e.deptno = d.deptno)
,xmlcomment('test')
),version '1.0') as result
from dept d where d.deptno=20;
ii. XMLATTRIBUTES: XMLAttributes is used to specify the values for the attributes of
the root element. Function XMLAttributes can be used only in a call to function
XMLElement.
Syntax: xmlAttributes(column1 as “AttributeName”, column2 as
“AttributeName”,…….)
Scenario1:
select xmlroot(xmlelement("Employee", xmlattributes(empno as "Empno")
, xmlelement ("Ename" , ename)
, xmlelement ("Salary", sal)
),version '1.0')
from emp e
where rownum<2;
iii. XMLFOREST: XMLForest produces a forest of XMLElements from its arguments.
Syntax: XMLForest(column1 [as “AttributeName”] , column2 as [“AttributeName”], ..)
XMLForest doesn’t produce empty tags whereas xmlelement does.
Eg1: select xmlroot(xmlagg(xmlelement ("Employee",xmlforest( e.EmpNO as "EmpNO"
,e.eNAME as "EmpName"
,e.comm as "Comission"
)) ),version '1.0') result from emp e where deptno=30 group
by deptno;
iv. XMLCONCAT: XMLConcat concatenates all of its arguments to create an XML
fragment.
Syntax: XMLConcat(XMLType1, XMLType2,…….)
Eg1:
Before concatenation:
select xmlelement("Empno",empno)
, xmlelement ("Ename" , ename)
, xmlelement ("Salary", sal) from emp e where rownum<3;
After Concatenation:
select xmlconcat(xmlelement("Empno",empno)
, xmlelement ("Ename" , ename)
, xmlelement ("Salary", sal)) from emp e where rownum<3;
v. XMLAGG: XMLAgg is an aggregate function that produces a forest of XMLElements
from a collection of XML elements.
Syntax: XMLElement(“TagName”, XMLAgg(XMLType1 order by column )
XMLAgg can also be used to concatenate xmltype instances across rows.
Eg1: --Query for generating an xml using xml/sql function xmlagg and order by clause.
select xmlroot(xmlelement("Main",xmlagg( xmlelement("Test", xmlcomment ('xmlagg
method with order by clause')
, xmlelement ("EmpNO",e.empno)
, xmlelement ("EmpName",e.ename)
, xmlelement ("Job",e.JOB)
, xmlelement ("DepartmentNO",e.deptno)
) order by empno
)
),VERSION '1.0'
) as "XMLAGG Order By Example" from emp e where deptno in(10,50);
--Query for generating an xml using xml/sql function xmlagg and group by clause.
select xmlroot(xmlelement("Main",xmlagg(xmlelement("Test" , xmlcomment ('xmlagg
method with group by clause')
, xmlelement ("EmpNO",e.empno)
, xmlelement ("EmpName",e.ename)
, xmlelement ("Job",e.JOB)
, xmlelement ("DepartmentNO",e.deptno)
)
)
),VERSION '1.0'
) as testv from emp e group by e.deptno;
vi. XMLPI: XMLPI is uesd to generate XML processing instructions.A processing
instruction is commonly used to provide to application information that is associated with
all or part of an XML document. The application uses the processing instruction to
determine how best to process the XML document.
Syntax: XMLPI([Name] identifier, ‘ value_expr ‘)
select xmlroot(xmlconcat( xmlcomment('Using XMLPI to provide process instructions')
,XMLPI(NAME "xml-stylesheet",'type="text/css" href="test.css"')
,xmlelement("Main",xmlagg(xmlelement("Test", xmlcomment ('xmlagg method with
order by clause')
, xmlelement ("EmpNO",e.empno)
, xmlelement ("EmpName",e.ename)
, xmlelement ("Job",e.JOB)
, xmlelement ("DepartmentNO",e.deptno) ) order by deptno ) )
),VERSION '1.0'
) as testv from emp e where deptno=50;
The above highlighted part shows the processing instructions that are used to process the
xml.
vii. XMLCOMMENT: XMLComment is used to generate XML comments.
Syntax: xmlcomment(‘expression/comment’)
Eg1: select xmlroot(xmlelement("EmpDetails",xmlcomment('Example For XML
Comment')
,xmlelement("Empno",empno), xmlelement("EmpName",ename)),version '1.0')
from emp where rownum<3;
viii. XMLROOT: XMLRoot is used to add a VERSION property, and optionally a
STANDALONE property, to the root information item of an XML value.
Syntax: XMLRoot(value_expr, version [value_expr],[standalone yes/no[value]])
Eg1: select xmlroot(xmlelement("EmpDetails",xmlelement("Empno",empno),
xmlelement("EmpName",ename)), version '1.0') "XMLROOT Example"
from emp where rownum<3;
ix. XMLSERIALIZE: XMLSerialize is used to obtain a string or a LOB representation of
XML data. Default datatype after conversion is CLOB.
Syntax: XMLSerialize(document/content value_expr [as datatype])
If type is ‘document’ then the input xml should be well-format single root document
otherwise gives error. If ‘content’ the input xml is not validated.
Eg1: select xmlserialize(document xmlelement("Empno",empno) as clob) from emp
where rownum<3;
x. XMLPARSE: XMLParse is used to parse a string containing XML data and generate a
corresponding value of XMLType.
Syntax: XMLParse(document/content ‘value_expr’ [wellformed])
select XMLParse(document '<Empno>1111</Empno>' WELLFORMED) from emp
where rownum<3;
2. Generating XML Using Oracle Database SQL Functions
i. XMLCOLATTVAL: XMLColAttVal is used to generate a forest of XML column
elements containing the values of the arguments passed in.
Syntax: XMLColAttval(column1 [as aliasname],column2 [as aliasname]…..)
Eg1: SELECT xmlroot(XMLElement("Emp", XMLAttributes(e.ename AS "FullName" )
, XMLColAttVal (e.hiredate, e.deptno AS "Department")
), version '1.0') AS "RESULT"
FROM emp e
WHERE e.deptno = 20;
<?xml version="1.0"?>
<Emp FullName="JONES">
<column name="HIREDATE">1981-04-02</column>
<column name="Department">20</column>
</Emp>
ii. XMLCDATA: XMLCDATA is used to generate an XML CDATA section.
XMLCDATA will not be parsed by the xmlparser. We can pass some text like javascript
containing special characters using XMLCDATA(XML Unparsed character data).The
term CDATA is used about text data that should not be parsed by the XML
parser.Characters like "<" and "&" are illegal in XML elements."<" will generate an error
because the parser interprets it as the start of a new element."&" will generate an error
because the parser interprets it as the start of an character entity. Some text, like
JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can
be defined as CDATA.
Syntax: xmlcdata(‘ cdata expression ‘)
Scenario1: To pass test containing special characters like ‘&’, ‘<’ and ‘@’
select XMLParse(document '<?xml version="1.0"?>
<Main>
<EmpName>JONES</EmpName>
<Testcode>@Test for cdata &a < &b</Testcode>
</Main>') "Result" fromdual;
The highlighted above tag contains the special symbols like ‘&’ and ‘<’ which causes the error
while parsing, as parser interprets
 ‘<’ as starting of a newtag.
 ‘&’ as starting of a character set.
select XMLParse(document '<?xml version="1.0"?>
<Main>
<EmpName>JONES</EmpName>
<![CDATA[@Test for cdata &a &b]]>
</Main>') "Result" fromdual;
The highlighted above part of xml contains special characters but doesn’t gives error as it
is part of ‘cdata’ tag. XML parser doesn’t process the data inside ‘cdata’ tag.
iii. SYS_XMLGEN: It takes either a ‘Scalar Value’ or ‘Object Type’, or ‘XMLType’
instance and converts to an XML document.
Syntax: SYS_XMLGen(columnname [,fmt])
Eg1:
select sys_xmlgen(ename)as "Ename" from emp where deptno=20;
Eg2:
select sys_xmlgen(sal*2)as "Salary" from emp where deptno=20;
Eg3:
select sys_xmlgen(sal*2,XMLFormat.createformat('Salary')) as "Salary" from emp where
deptno=20;
Eg4: query for generating nested xml using sys_xmlgen
Step1: create object types for tables that need to be part of xml with corresponding tag
names. These may include data columns and also object types.
Step2: create a type of object, so that it can be used in creation of another type object.
Step3: develop a query to produce the xml using the data type objects created.
drop type "DeptXML";
drop type "EmpXML1";
drop type "EmpXML";
/
Step1: create or replace type "EmpXML" as object
("EmpNO" number
,"Ename" varchar2(10)
,"DeptNo" number );
/
Step2: create or replace type "EmpXML1" as table of "EmpXML";
/
Step1: create or replace type "DeptXML" as object
("DeptNO" number, "DeptName" varchar2(14),"Location"
varchar2(13),"DeptEmp" "EmpXML1");
/
Step3: select sys_xmlgen("DeptXML"( deptno,dname,loc,cast(multiset( select
"EmpXML"(e.empno,e.ename,e.deptno)
from emp e
where e.deptno = d.deptno
) as "EmpXML1"
)
)
,XMLFormat.createFormat('XMLTEST')
) as deptxml
from dept d
where d.deptno=20;
iv. SYS_XMLAGG:SYS_XMLAgg aggregates all XML documents or fragments
represented by expr and produce a single XML document. It adds a new enclosing
element with a default name, ROWSET. To format the XML document differently, we
can use fmt parameter.
Syntax: SYS_XMLAgg(columnname [,fmt])
Scenario1: Using sys_xmlagg without using format parameter.
select sys_xmlagg(sys_xmlgen(sal*2,XMLFormat.createformat('Salary'))) as "Salary"
from emp where deptno=20;
As we haven’t specified any format parameter for the sys_xmlagg tag, it adds the default
rowset tag to xml formed by aggregating the xml fragments.
Eg2: Using sys_xmlagg with using format parameter.
select
sys_xmlagg(sys_xmlgen(sal*2,XMLFormat.createformat('Salary')),XMLFormat.createfor
mat('Employee'))
as "Salary" from emp where deptno=20;
As we have specified the xmlformat parameter it displays data inside ‘Employee’ tag.
3. Generating XML Using DBMS_XMLGEN:
DBMS_XMLGEN package provides various methods to manipulate the xmldata like
newcontext(), setrowtag(), setrowsettag(),getxml().getxmltype(),setMaxRows() e.t.c
Overview of XML Generation Using DBMS_XMLGEN:
The steps are as follows:
i. Get the context from the package by supplying a SQL query and calling the newContext()
call.
ii. Pass the context to all procedures or functions in the package to set the various options.
For example, to set the ROW element name, use setRowTag(ctx), where ctx is the context
got from the previous newContext() call.
iii. Get the XML result, using getXML() or getXMLType(). By setting the maximum
number of rows to be retrieved for each fetch using setMaxRows(), you can call either of
these functions repeatedly, retrieving up to the maximum number of rows for each call.
These functions return XML data (as a CLOB value and as an instance of XMLType,
respectively), unless there are no rows retrieved; in that case, these functions return
NULL. To determine how many rows were retrieved, use function
getNumRowsProcessed().
iv. You can reset the query to start again and repeat step 3.
v. Close the closeContext() to free up any resource allocated inside.
vi. In conjunction with a SQL query, method DBMS_XMLGEN.getXML() typically returns
a result like the following as a CLOB value:
Example:
Scenario1: Query for generating xml using dbms_xmlgen
drop type d1;
drop type e2;
drop type "EmpDetails";
/
create or replace type "EmpDetails" as object( Empno NUMBER(4)
,Empname varchar2(10)
,salary number(7,2)
);
/
create or replace type e2 as table of "EmpDetails";
/
create or replace type d1 as object( deptno number(2)
,deptname varchar2(14)
,location varchar2(13)
,"Employees" e2
);
/
select dbms_xmlgen.getxml('select d1( d.deptno
,d.dname
,d.loc
,cast(multiset( select e.empno,e.ename,e.sal
from emp e
where e.deptno = d.deptno
) as e2
)
) as testxml
from dept d'
)as result
from dual;
4. Generating XML Using XSQL Pages Publishing Framework.
The Oracle XSQL Pages publishing framework is an extensible platform for easily
publishing XML information in any format you desire. It greatly simplifies combining
the power of SQL, XML, and XSLT to publish dynamic web content based on database
information.
5. Generating XML Using XML SQL Utility (XSU)
Using the XSQL publishing framework, anyone familiar with SQL can create and use
declarative templates called "XSQL pages" to:
 Assemble dynamic XML "datagrams" based on parameterized SQL queries, and
 Transform these "data pages" to produce a final result in any desired XML, HTMLor
text-based format using an associated XSLT transformation.
XML SQL Utility (XSU) is an XDK component that enables you to transfer XML data
through Oracle SQL statements. You can use XSU to perform the following tasks:
 Transform data in object-relational database tables or views into XML. XSU can
query the database and return the result set as an XML document.
 Extract data from an XML document and use canonical mapping to insert the data
into a table or a view or update or delete values of the appropriate columns or
attributes.
6. Generating XML with Oracle XML DB.
Oracle XML DB is a high-performance, native XML storage and retrieval technology
that is delivered as a part of all versions of Oracle Database. Oracle XML DB provides
full support for all of the key XML standards, including XML, Namespaces, DOM,
XQuery, SQL/XML and XSLT. By providing full support for XML standards, Oracle
XML DB supports native XML application development. Application developers are able
to use XML-centric techniques to store, manage, organize, and manipulate XML content
stored in the database. Oracle XML DB also supports the SQL/XML standard, which
allows SQL-centric development techniques to be used to publish XML directly from
relational data stored in Oracle Database 12c. With Oracle XML DB, you get all the
advantages of relational database technology plus all the advantages of the W3C's XML
standards.
XML ExtractionIn Oracle
XML data can be extracted from XMLType columns in the following ways:
i) By selecting XMLType columns through SQL(post-11g)
 xmltable function
 xmlexists function
 XMLQuery function
 XMLCast function
ii) By querying XMLType columns directly(pre-11g)
 existsNode() function
 extract() function
 extractvalue() function
 xmlsequence function
 Extracting element attributes
 XML unnesting
i) By selecting XMLType columns through SQL(post-11g)
1) XMLTable function
1. It is an SQL table function that uses XQuery expressions to create relational rows from an
XML input document. Its result is queried as a virtual relational table using SQL.
It contains one row-generating XQuery expression and, in the COLUMNS clause, one or
multiple column-generating expressions.
Syntax :
XMLTable([XMLnamespaces_clause]'<XQuery>'
PASSING <xml column>
COLUMNS <new column name>
<column type> PATH <XQuery path>)
 The XMLNAMESPACES clause contains a set of XML namespace declarations. These
declarations are referenced by the XQuery expression, which computes the row, and by the
XPath expression in the PATH clause of XML_table_column, which computes the
columns for the entire XMLTable function. If we want to use qualified names in the PATH
expressions of the COLUMNS clause, then we need to specify the XMLNAMESPACES
clause.
XMLNAMESPACES
( [ string AS identifier ]
[ [, string AS identifier ]
]...
[ DEFAULT string ] )
XML namespaces are used for providing uniquely named elements and attributes in an
XML document. They are defined in a W3C recommendation. An XML instance may
contain element or attribute names from more than one XML vocabulary. If each
vocabulary is given a namespace, the ambiguity between identically named elements or
attributes can be resolved.
A namespace name is a uniform resource identifier (URI). Typically, the URI chosen for
the namespace of a given XML vocabulary describes a resource under the control of the
author or organization defining the vocabulary, such as a URL for the author's Web server.
However, the namespace specification does not require nor suggest that the namespace
URI be used to retrieve information; it is simply treated by an XML parser as a string.
 XQuery is a complete XQuery expression and can include prolog declarations.
 The expr in the XML_passing_clause is an expression returning an XMLType or an
instance of a SQL scalar datatype that is used as the context for evaluating the XQuery
expression. We can specify only one expr in the PASSING clause without an identifier.
The result of evaluating each expr is bound to the corresponding identifier in the
XQuery_string. If any expr that is not followed by an AS clause, then the result of
evaluating that expression is used as the context item for evaluating the XQuery_string.
PASSING [ BY VALUE ]
expr [ AS identifier ]
[, expr [ AS identifier ]
]...
 The COLUMNS clause is used to transform XML data into relational data. Each of the
entries in this clause defines a column with a column name and a SQL data type. The
optional COLUMNS clause defines the columns of the virtual table to be created by
XMLTable.
 If we omit the COLUMNS clause, then XMLTable returns a row with a single XMLType
pseudo column named COLUMN_VALUE.
 The datatype is required unless XMLTable is used with XML schema-based storage of
XMLType, datatype. In this case, if we omit datatype, Oracle XML DB infers the datatype
from the XML schema. If the database is unable to determine the proper type for a node,
then a default type of VARCHAR2(4000) is used.
 FOR ORDINALITY specifies that column is to be a column of generated row numbers.
There must be at most one FOR ORDINALITY clause. It is created as a NUMBER
column.
column
{ FOR ORDINALITY
| datatype [ PATH string ] [ DEFAULT expr ]}
 The optional PATH clause specifies that the portion of the XQuery result that is addressed
by XQuery expression string is to be used as the column content. If we omit PATH, then
the XQuery expression column is assumed. For example:
XMLTable(... COLUMNS xyz
is equivalent to
XMLTable(... COLUMNS xyz PATH 'XYZ')
We can use different PATH clauses to split the XQuery result into different virtual-table
columns.
 The optional DEFAULT clause specifies the value to use when the PATH expression
results in an empty sequence. Its expr is an XQuery expression that is evaluated to produce
the default value.
XMLTable ([ XMLnamespaces_clause , ] '<XQuery>' PASSING <xml column>
COLUMNS <new column name> <column type> PATH <XQuery path>)
Example:
Consider a table XML_TEMP_TABLE which holds some XML data. Below is the create
statement this table.
CREATE TABLE XML_TEMP_TABLE
( XML_CLOB CLOB
) ;
We will use the following XML document :
Employee.xml
Below INSERT statement add one record having some XML content in it.
INSERT INTO XML_TEMP_TABLE VALUES('<?xml version="1.0" encoding="utf-
8"?><Employees xmlns="http://www.w3.org/1999/xml"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Employee
EmpNo="5000"><Ename>Test
User</Ename><Job>Clerk</Job><Mgr>7698</Mgr><HireDate>04-FEB-
14</HireDate><Sal>12500</Sal><Comm/><Department><DeptNo>50</DeptNo><
Dname/><Address><State>TEXAS</State><City>Dallas</City><Pincode>3412648</
Pincode></Address></Department></Employee><Employee
EmpNo="5001"><Ename>Test
User1</Ename><Job>MANAGER</Job><Mgr>7839</Mgr><HireDate>09-JUN-
81</HireDate><Sal>30000</Sal><Comm>100</Comm><Department><DeptNo/><
Dname/><Address><State/><City/><Pincode/></Address></Department></Employe
e></Employees>');
i) Reading Employee Name, Job, Department Name,City etc. of all employees using
XMLTable function. Consider the above XML has xmlns attribute, now we use
XMLNAMESPACES function to remove ambiguity between identically named
elements/attributes used in different XML vocabulary.
SELECT
x1.Ename,
x1.Job,
x1.Mgr,
to_date(x1.HireDate,'dd/mm/yyyy') HireDate,
x1.Sal,
x1.Comm,
x2.DeptNo,
x2.Dname,
x3.State,
x3.City,
x3.Pincode
FROM XML_TEMP_TABLE t ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS
Employee XMLTYPE PATH 'Employee')x ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Employee' PASSING x.Employee COLUMNS
Ename VARCHAR2(240) PATH 'Ename' ,
Job VARCHAR2(240) PATH 'Job' ,
Mgr NUMBER PATH 'Mgr' ,
HireDate VARCHAR2(240) PATH 'HireDate' ,
Sal NUMBER PATH 'Sal' ,
Comm NUMBER PATH 'Comm',
Department XMLTYPE PATH 'Department')x1,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Department' PASSING x1.Department COLUMNS
DeptNo NUMBER PATH 'DeptNo',
Dname VARCHAR2(240) PATH 'Dname',
Address XMLTYPE PATH 'Address') x2,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Address' PASSING x2.Address COLUMNS
State VARCHAR2(240) PATH 'State',
City VARCHAR2(240) PATH 'City',
Pincode NUMBER PATH 'Pincode') x3;
The passing clause defines that the xmltype(t.xml_clob) refers to the XML column data
of the table XML_TEMP_TABLE of data type xmltype. Employee details can be
defined using two different PATH expressions (by using row-generating expression
/Employees and Employee ) given above or can be written using single PATH
expression (by using row-generating expression /Employees/Employee) given below.
All Department details can be defined in different PATH expressions (by using row-
generating expression i.e. XQuery as Department, DeptNo, Dname) given above or
using single PATH expression (by using XQuery path //Department/DeptNo,
//Department/Dname, //Department/Loc) given below. Address details are extracted
only in above query(using one more PATH expression State, City, Pincode when we
want to extract multilevel XML document):
SELECT x.Ename,
x.Job,
x.Mgr,
to_date(x.HireDate,'dd/mm/yyyy') HireDate,
x.Sal,
x.Comm,
x.DeptNo,
x.Dname,
x.Loc
FROM XML_TEMP_TABLE t ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees/Employee' passing xmltype(t.xml_clob) columns
Ename VARCHAR2(240) path 'Ename' ,
Job VARCHAR2(240) path 'Job' ,
Mgr NUMBER path 'Mgr' ,
HireDate VARCHAR2(240) path 'HireDate' ,
Sal NUMBER path 'Sal' ,
Comm NUMBER path 'Comm',
DeptNo NUMBER path '//Department/DeptNo',
Dname VARCHAR2(240) path '//Department/Dname',
Loc VARCHAR2(240) path '//Department/Loc')x ;
ii) Rows with a single XMLType pseudo column named COLUMN_VALUE when
columns clause is omitted.
SELECT x.*
FROM XML_TEMP_TABLE t ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees/Employee' passing xmltype(t.xml_clob) )x ;
iii) To retrieve attribute value EmpNo from the xml, @ is used.
SELECT x1.EmpNo
FROM XML_TEMP_TABLE t ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees' passing xmltype(t.xml_clob) columns Employee xmltype path
'Employee')x ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee'
passing x.Employee columns EmpNo NUMBER path '@EmpNo') x1;
iv) Reading Employee Name of all employees using selection of given current node.
SELECT x.Ename
FROM XML_TEMP_TABLE t ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees/Employee/Ename' passing xmltype(t.xml_clob) columns
Ename VARCHAR2(240) path '.' )x ;
v) To fetch the text value of currently selected node item i.e. here Employee Name, select
path as /Employee/Ename and then use text() expression to get the value of this selected
node.
SELECT x1.Ename
FROM XML_TEMP_TABLE t ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees' passing xmltype(t.xml_clob) columns Employee xmltype path
'Employee')x ,
xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml')
,'Employee/Ename' passing x.Employee columns Ename VARCHAR2(240) path
'text()') x1;
Along with text() expression, Oracle provides various other useful expressions. For
example item(), node(), attribute(), element(), document-node(), namespace(), text(),
xs:integer, xs:string.
vi)To fetch all employees whose salary is greater than 15000, we can give this condition in
XQuery expression.
SELECT
x1.Ename,
x1.Job,
x1.Mgr,
to_date(x1.HireDate,'dd/mm/yyyy') HireDate,
x1.Sal,
x1.Comm,
x2.DeptNo,
x2.Dname,
x3.State,
x3.City,
x3.Pincode
FROM XML_TEMP_TABLE t ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS
Employee XMLTYPE PATH 'Employee')x ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Employee[Sal > 15000]' PASSING x.Employee COLUMNS
Ename VARCHAR2(240) PATH 'Ename' ,
Job VARCHAR2(240) PATH 'Job' ,
Mgr NUMBER PATH 'Mgr' ,
HireDate VARCHAR2(240) PATH 'HireDate' ,
Sal NUMBER PATH 'Sal' ,
Comm NUMBER PATH 'Comm',
Department XMLTYPE PATH 'Department')x1,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Department' PASSING x1.Department COLUMNS
DeptNo NUMBER PATH 'DeptNo',
Dname VARCHAR2(240) PATH 'Dname',
Address XMLTYPE PATH 'Address') x2,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Address' PASSING x2.Address COLUMNS
State VARCHAR2(240) PATH 'State',
City VARCHAR2(240) PATH 'City',
Pincode NUMBER PATH 'Pincode') x3;
In certain cases, Employees may not have department and address information, then the
respective nodes are missing for Department and Address, then to cater parent elements
without child elements we have to use the correlated FROM "outer join" syntax, which
involves placing the Oracle outer join operator, i.e. (+), on the "child" (i.e. "deficient" i.e.
for Department and Address) component of the FROM clause as given below.
SELECT
x1.Ename,
x1.Job,
x1.Mgr,
to_date(x1.HireDate,'dd/mm/yyyy') HireDate,
x1.Sal,
x1.Comm,
x2.DeptNo,
x2.Dname,
x3.State,
x3.City,
x3.Pincode
FROM XML_TEMP_TABLE t ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS
Employee XMLTYPE PATH 'Employee')x ,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Employee[Sal > 15000]' PASSING x.Employee COLUMNS
Ename VARCHAR2(240) PATH 'Ename' ,
Job VARCHAR2(240) PATH 'Job' ,
Mgr NUMBER PATH 'Mgr' ,
HireDate VARCHAR2(240) PATH 'HireDate' ,
Sal NUMBER PATH 'Sal' ,
Comm NUMBER PATH 'Comm',
Department XMLTYPE PATH 'Department')x1,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Department' PASSING x1.Department COLUMNS
DeptNo NUMBER PATH 'DeptNo',
Dname VARCHAR2(240) PATH 'Dname',
Address XMLTYPE PATH 'Address') (+) x2,
XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml')
,'Address' PASSING x2.Address COLUMNS
State VARCHAR2(240) PATH 'State',
City VARCHAR2(240) PATH 'City',
Pincode NUMBER PATH 'Pincode')(+) x3;
vii) Usage of Xpath syntax. We will use the following XML document in the examples
below.
bookstore.xml
Selecting Nodes : XPath uses path expressions to select nodes in an XML document.
The node is selected by following a path or steps. The most useful path expressions are
listed below:
Expression Description
nodename Selects all nodes with the name “nodename”
/ Selects from the root node
//
Selects nodes in the document from the current node that match
the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes
In the table below we have listed some path expressions and the result of the expressions:
Path Expression Result
Bookstore Selects all nodes with the name “bookstore”
/bookstore
Selects the root element bookstore
Note: If the path starts with a slash ( / ) it always
represents an absolute path to an element!
Bookstore/book Selects all book elements that are children of bookstore
//book
Selects all book elements no matter where they are in
the document
bookstore//book
Selects all book elements that are descendant of the
bookstore element, no matter where they are under the
bookstore element
//@lang Selects all attributes that are named lang
Predicates : Predicates are used to find a specific node or a node that contains a specific
value embedded in square brackets. In the table below we have listed some path
expressions with predicates and the result of the expressions:
Path Expression Result
/bookstore/book[1]
Selects the first book element that is the child of
the bookstore element.
Note: In IE 5,6,7,8,9 first node is[0], but
according to W3C, it is [1]. To solve this
problem in IE, set the SelectionLanguage to
XPath:
In JavaScript:
xml.setProperty("SelectionLanguage","XPath");
/bookstore/book[last()]
Selects the last book element that is the child of
the bookstore element
/bookstore/book[last()-1]
Selects the last but one book element that is the
child of the bookstore element
/bookstore/book[position()<3]
Selects the first two book elements that are
children of the bookstore element
//title[@lang]
Selects all the title elements that have an
attribute named lang
//title[@lang='eng']
Selects all the title elements that have an
attribute named lang with a value of 'eng'
/bookstore/book[price>35.00]
Selects all the book elements of the bookstore
element that have a price element with a value
greater than 35.00
/bookstore/book[price>35.00]/title
Selects all the title elements of the book
elements of the bookstore element that have a
price element with a value greater than 35.00
Selecting Unknown Nodes : XPath wildcards can be used to select unknown XML
elements.
Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind
In the table below we have listed some path expressions and the result of the
expressions:
Path Expression Result
/bookstore/* Selects all the child nodes of the bookstore element
//* Selects all elements in the document
//title[@*] Selects all title elements which have any attribute
Selecting Several Paths : By using the | operator in an XPath expression we can select
several paths. In the table below we have listed some path expressions and the result of
the expressions:
Path Expression Result
//book/title |
//book/price
Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the
document
/bookstore/book/title |
//price
Selects all the title elements of the book element of the
bookstore element AND all the price elements in the
document
2) XMLEXISTS function
It is an SQL function that can be used wherever a BOOLEAN datatype can be used, such as in
predicate or in a CASE statement. It is used to determine if a given XML node exists in an
XML document. The functional equivalent of this prior to the appearance of this function was
either the EXISTSNODE function, but EXISTSNODE returns a numeric 1 or 0, not a
BOOLEAN, or to do the check via XPath in XMLTABLE (or via EXTRACT).
The use of XMLExists is limited to a SQL WHERE clause or CASE expression. If we need to
use XMLExists in a SELECT list, then we wrap it in a CASE expression:
CASE WHEN XMLExists(...) THEN 'TRUE' ELSE 'FALSE' END
Syntax :
XMLEXISTS(<xpath/xquery> PASSING <xmltype document>)
e.g. assuming that table XXT_PURCHASEORDER has an XMLTYPE column
SELECT OBJECT_VALUE
FROM XXT_PURCHASEORDER
WHERE XMLExists('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]'
PASSING OBJECT_VALUE);
SELECT CASE WHEN XMLEXISTS('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]'
PASSING XP.OBJECT_VALUE) THEN 'TRUE' ELSE 'FALSE' END "CASE_RESULT"
FROM XXT_PURCHASEORDER XP;
3) XMLQuery Function
We use XMLQuery function to construct or query XML data. This function takes as
arguments an XQuery expression, as a string literal, and an optional XQuery context item, as a
SQL expression. The context item establishes the XPath context in which the XQuery
expression is evaluated. Additionally, XMLQuery accepts as arguments any number of SQL
expressions whose values are bound to XQuery variables during the XQuery expression
evaluation. The function returns the result of evaluating the XQuery expression, as an
XMLType instance.
Syntax :
XMLQUERY
( XQuery_string
[ XML_passing_clause ]
RETURNING CONTENT [ NULL ON EMPTY ])
 XQuery_string is a complete XQuery expression, possibly including a prolog, as a literal
string.
 The XML_passing_clause is the keyword PASSING followed by one or more SQL
expressions (expr) that each return an XMLType instance or an instance of a SQL scalar
data type (that is, not an object or collection data type). Each expression (expr) can be a
table or view column value, a PL/SQL variable, or a bind variable with proper casting. All
but possibly one of the expressions must each be followed by the keyword AS and an
XQuery identifier. The result of evaluating each expr is bound to the corresponding
identifier for the evaluation of XQuery_string. If there is an expr that is not followed by an
AS clause, then the result of evaluating that expr is used as the context item for evaluating
XQuery_string
 RETURNING CONTENT indicates that the value returned by an application of
XMLQuery is an instance of parameterized XML type XML(CONTENT), not
parameterized type XML(SEQUENCE). It is a document fragment that conforms to the
extended Infoset data model. As such, it is a single document node with any number of
children. The children can each be of any XML node type; in particular, they can be text
nodes.
4) XMLCast Function
XMLCast function casts its first argument to the scalar SQL data type specified by its second
argument. The first argument is a SQL expression that is evaluated. Any of the following SQL
data types can be used as the second argument:
 NUMBER
 VARCHAR2
 CHAR
 CLOB
 BLOB
 REF XMLTYPE
 any SQL date or time data type
Syntax:
XMLCAST ( value_expression AS datatype )
The result of evaluating the first XMLCast argument is an XML value. It is converted to the
target SQL data type by using the XQuery atomization process and then casting the XQuery
atomic values to the target data type. If this conversion fails, then an error is raised. If
conversion succeeds, the result returned is an instance of the target data type.
Below example extracts the scalar value of XML Fragment (i.e. node REFERENCE) Using
XMLCast and XMLQuery functions.
SELECT XMLCast(XMLQuery('/PURCHASEORDER/REFERENCE' PASSING
OBJECT_VALUE RETURNING CONTENT)
AS VARCHAR2(100)) "REFERENCE"
FROM XXT_PURCHASEORDER
WHERE XMLExists('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]'
PASSING OBJECT_VALUE);
ii)We By querying XMLType columns directly
a) existsNode() function
Syntax :
existsNode(XMLType_instance IN XMLType,
XPath_string IN VARCHAR2, namespace_string IN varchar2 := null) RETURN NUMBER
The existsNode() XMLType function checks if the given XPath evaluation results in at least a
single XML element or text node. If so, it returns the numeric value 1, otherwise, it returns a
0. The namespace parameter can be used to identify the mapping of prefix(es) specified in the
XPath_string to the corresponding namespace(s).
Using existsNode() on XMLType
The following example demonstrates how to use existsNode() on an XMLType instance in a
query.
CREATE TABLE XXT_PURCHASEORDER OF XMLType;
/
INSERT INTO XXT_PURCHASEORDER
VALUES ('<PURCHASEORDER xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://localhost:8080/source/schemas/poSource/xsd/purc
haseOrder.xsd"><REFERENCE>SBELL-
2002100912333601PDT</REFERENCE><ACTIONS><ACTION><USER>SVOLLMAN</
USER></ACTION></ACTIONS><REJECT/><REQUESTOR>Sarah J.
Bell</REQUESTOR><USER>SBELL</USER><COSTCENTER>S30</COSTCENTER><S
HIPPINGINSTRUCTIONS><NAME>Sarah J. Bell</NAME><ADDRESS>400 Oracle
Parkway Redwood Shores CA 94065 USA</ADDRESS><TELEPHONE>650 506
7400</TELEPHONE></SHIPPINGINSTRUCTIONS><INSTRUCTIONS>Air
Mail</INSTRUCTIONS><LINEITEMS><LINEITEM
ITEMNUMBER="1"><DESCRIPTION>A Night to Remember</DESCRIPTION><PART
ID="715515009058" UNITPRICE="39.95" QUANTITY="2"/></LINEITEM><LINEITEM
ITEMNUMBER="2"><DESCRIPTION>The Unbearable Lightness Of
Being</DESCRIPTION><PART ID="37429140222" UNITPRICE="29.95"
QUANTITY="2"/></LINEITEM><LINEITEM
ITEMNUMBER="3"><DESCRIPTION>Sisters</DESCRIPTION><PART
ID="715515011020" UNITPRICE="29.95"
QUANTITY="4"/></LINEITEM></LINEITEMS></PURCHASEORDER>');
SELECT extract(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE"
FROM XXT_PURCHASEORDER
WHERE
existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1;
An XPath expression such as /PURCHASEORDER/REFERENCE results in a single node.
Therefore, existsNode() will return 1 for that XPath whereas
/PURCHASEORDER/REFERENCE/text(),results in a single text node. An XPath expression
such as /PO/POTYPE does not return any nodes. Therefore, an existsNode() on this would
return the value 0.It can be used in queries in the WHERE but never in the SELECT list and
to create function-based indexes to speed up evaluation of queries.
The following example uses existsNode() to select rows/find a node with INSTRUCTIONS set
to Air Mail.
SELECT object_value
FROM XXT_PURCHASEORDER
WHERE
existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1;
Using Indexes to Evaluate existsNode()
We can create function-based indexes using existsNode() to speed up the execution. We can
also create a CTXXPATH index to help speed up arbitrary XPath searching.
b) extract() function
The extract() XMLType function is similar to the existsNode() function. It applies a
VARCHAR2 XPath string with an optional namespace parameter and returns an XMLType
instance containing an XML fragment.
Syntax:
extract(XMLType_instance IN XMLType, XPath_string IN VARCHAR2,
namespace_string In varchar2 := null) RETURN XMLType;
extract() on XMLType extracts the node or a set of nodes from the document identified by the
XPath expression. The extracted nodes can be elements, attributes, or text nodes. If multiple
text nodes are referenced in the XPath, the text nodes are collapsed into a single text node
value. Namespace can be used to supply namespace information for prefixes in the XPath
string.
The XMLType resulting from applying an XPath through extract() need not be a well-formed
XML document but can contain a set of nodes or simple scalar data. We can use the
getStringVal() or getNumberVal() methods on XMLType to extract the scalar data.
A text node is considered an XMLType. In other words, extract(object_value,
'/PURCHASEORDER/REFERENCE/text()') still returns an XMLtype instance although the
instance may actually contain only text. We can use getStringVal() to get the text value out as
a VARCHAR2 result. To identify text nodes in elements, text() node test function is used
before using the getStringVal() or getNumberVal() to convert them to SQL data or else it
produces an XML fragment.
For example, XPath expressions:
 /PURCHASEORDER/REFERENCE identifies the fragment <REFERENCE>...</
REFERENCE >
 /PURCHASEORDER/REFERENCE/text() identifies the value of the text node of the
Reference element.
We can use the index mechanism to identify individual elements in case of repeated elements
in an XML document. For example, if we have an XML document such as:
PURCHASEORDER.x
ml
then we can use:
 // LINEITEM [1] to identify the first LineItem element.
 // LINEITEM [2] to identify the second LineItem element.
The result of extract() is always an XMLType. If applying the XPath produces an empty set,
then extract() returns a NULL value.Hence it’s used to extract:
 Numerical values on which function-based indexes can be created to speed up processing
 Collection expressions for use in the FROM clause of SQL statements
 Fragments for later aggregation to produce different documents
The following example uses extract() to query the value of the REFERENCE column or Node
for orders with INSTRUCTIONS set to Air Mail.
SELECT extract(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE"
FROM XXT_PURCHASEORDER
WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1;
Functions extract().getStringVal() and extractValue() differ in their treatment of entity
encoding. Function extractValue() unescapes any encoded entities; extract().getStringVal()
returns the data with entity encoding intact.
c) extractValue() Function
The extractvalue() XMLType function takes as arguments an XMLType instance and an
XPath expression. It returns a scalar value corresponding to the result of the XPath evaluation
on the XMLType instance.
 XML schema-based documents. For documents based on XML schema, if Oracle Database
can infer the type of the return value, then a scalar value of the appropriate type is returned.
Otherwise, the result is of type VARCHAR2.
 Non- schema-based documents. If the extractValue() query can potentially be re-written,
such as when the query is over a SQL/XML view, then a scalar value of the appropriate
type is returned. Otherwise, the result is of type VARCHAR2.
The extractValue() function attempts to determine the proper return type from the XML
schema of the document, or from other information such as the SQL/XML view else returns a
VARCHAR2. With XML schema-based content, extractValue() returns the underlying
datatype in most cases. For CLOB datatypes, it will return the CLOB directly.
If a specific datatype is desired, conversion functions such as to_char or to_date can be put
around the extractValue() function call or around an extract.getStringVal(). This can help
maintain consistency between different queries regardless of whether the queries can be
rewritten.
Syntax : EXTRACTVALUE ( XMLType_instance, XPath_string [, namespace_string] )
A Shortcut Function
extractValue() permits us to extract the desired value more easily than when using the
equivalent extract() function. It is an ease-of-use and shortcut function. So instead of using:
extract(x,'path/text()').get(string|number)val()
we can replace extract().getStringVal() or extract().getnumberval() with extractValue() as
follows:
extractValue(x, 'path/text()')
With extractValue() we can leave off the text(), but ONLY if the node pointed to by the 'path'
part has only one child and that child is a text node. Otherwise, an error is
thrown.extractValue() has the same syntax as extract().
extractValue() Characteristics
 It always returns only scalar content, such as NUMBER, VARCHAR2, and so on.
 It cannot return XML nodes or mixed content. It raises an error at compile or run time if it
gets XML nodes as the result.
 It always returns VARCHAR2 by default. If the node value is bigger than 4K, a runtime
error occurs.
 In the presence of XML schema information, at compile time, extractValue() can
automatically return the appropriate datatype based on the XML schema information, if it
can detect so at compile time of the query. For instance, if the XML schema information
for the path /PO/POID indicates that this is a numerical value, then extractValue() returns a
NUMBER.
 If the extractValue() is on top of a SQL/XML view and the type can be determined at
compile time, the appropriate type is returned.
 If the XPath identifies a node, then it automatically gets the scalar content from its text
child. The node must have exactly one text child. For example:
extractValue(xmlinstance, ' /PURCHASEORDER/REFERENCE’)
extracts out the text child of Reference. This is equivalent to:
extract(xmlinstance, ' /PURCHASEORDER/REFERENCE/text()').getstringval()
Below query extracts the scalar value of the REFERENCE column/ XML Fragment using
extractValue() function. This is in contrast to the extract() function where the entire
<REFERENCE> element is extracted.
SELECT extractValue(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE"
FROM XXT_PURCHASEORDER
WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1;
Functions extract().getStringVal() and extractValue() differ in their treatment of entity
encoding. Function extractValue() unescapes any encoded entities; extract().getStringVal()
returns the data with entity encoding intact.
Querying XML Data With SQL
Below performs a query of data(XMLType) in given rows using extractValue() and
existsNode()
SELECT extractValue(object_value,'/PURCHASEORDER/REFERENCE') REFERENCE,
extractValue(object_value,'/PURCHASEORDER/*//USER') USERID,
case
when
existsNode(object_value,'/PURCHASEORDER/LINEITEMS/LINEITEM[DESCRIPT
ION="A Night to Remember"]') = 1
then 'Accepted'
else 'Rejected'
end "STATUS",
extractValue(object_value,'//COSTCENTER') COSTCENTER
FROM XXT_PURCHASEORDER
WHERE existsNode(object_value,'//COSTCENTER') = 1
ORDER By extractValue(object_value,'//REFERENCE');
Below example demonstrates using a cursor in PL/SQL to query XML data. A local XMLType
instance is used to store transient data.
declare
xNode XMLType;
vText VARCHAR2(256);
vReference VARCHAR2(32);
cursor getPurchaseOrder (REFERENCE in VARCHAR2) is
SELECT object_value XML
FROM XXT_PURCHASEORDER
WHERE
EXISTSNODE(object_value,'/PURCHASEORDER[REFERENCE="'|| REFERENCE || '"]')
= 1;
begin
vReference := 'SBELL-2002100912333601PDT';
FOR c IN getPurchaseOrder(vReference)
LOOP
xNode := c.XML.extract('//REQUESTOR');
vText := xNode.extract('//text()').getStringVal();
dbms_output.put_line(' The Requestor for Reference ' || vReference ||
' is '|| vText);
END LOOP;
vReference := 'SBELL-2002100912333601PDT';
FOR c IN getPurchaseOrder(vReference)
LOOP
xNode := c.XML.extract('//LINEITEM[@ITEMNUMBER="1"]/DESCRIPTION');
vText := xNode.extract('//text()').getStringVal();
dbms_output.put_line(' The Description of LineItem[1] for Reference '
|| vReference || ' is '|| vText);
END LOOP;
end;
Below example shows how to extract data from an XML purchase order and insert it into a
SQL relational table using the extract() function.
create table PURCHASEORDER_TABLE(
REFERENCE VARCHAR2(28) PRIMARY KEY,
REQUESTER VARCHAR2(48),
ACTIONS XMLTYPE,
USERID VARCHAR2(32),
COSTCENTER VARCHAR2(3),
SHIPTONAME VARCHAR2(48),
ADDRESS VARCHAR2(512),
PHONE VARCHAR2(32),
SPECIALINSTRUCTIONS VARCHAR2(2048)
);
create table PURCHASEORDER_LINEITEM(
REFERENCE,
FOREIGN KEY ("REFERENCE") REFERENCES "PURCHASEORDER_TABLE"
("REFERENCE") ON DELETE CASCADE,
LINENO NUMBER(10),
PRIMARY KEY ("REFERENCE","LINENO"),
UPC VARCHAR2(14),
DESCRIPTION VARCHAR2(128),
QUANTITY NUMBER(10),
UNITPRICE NUMBER(12,2)
);
insert into PURCHASEORDER_TABLE(
REFERENCE,
REQUESTER,
ACTIONS,
USERID,
COSTCENTER,
SHIPTONAME,
ADDRESS,
PHONE,
SPECIALINSTRUCTIONS)
select
x.object_value.extract('/PURCHASEORDER/REFERENCE/text()').getStringVal(),
x.object_value.extract('/PURCHASEORDER/REQUESTOR/text()').getStringVal(),
x.object_value.extract('/PURCHASEORDER/ACTIONS'),
x.object_value.extract('/PURCHASEORDER/USER/text()').getStringVal(),
x.object_value.extract('/PURCHASEORDER/COSTCENTER/text()').getStringVal(),
x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/NAME/text()').getSt
ringVal(),
x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/ADDRESS/text()').g
etStringVal(),
x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/TELEPHONE/text(
)').getStringVal(),
x.object_value.extract('/PURCHASEORDER/INSTRUCTIONS/text()').getStringVal()
from XXT_PURCHASEORDER x
where x.object_value.existsNode('/PURCHASEORDER[REFERENCE="SBELL-
2002100912333601PDT"]') = 1;
insert into PURCHASEORDER_LINEITEM(
REFERENCE,
LINENO,
UPC,
DESCRIPTION,
QUANTITY,
UNITPRICE)
select
x.object_value.extract('/PURCHASEORDER/REFERENCE/text()').getStringVal(),
value(l).extract('/LINEITEM/@ITEMNUMBER').getNumberVal(),
value(l).extract('/LINEITEM/PART/@ID').getNumberVal(),
value(l).extract('/LINEITEM/DESCRIPTION/text()').getStringVal(),
value(l).extract('/LINEITEM/PART/@QUANTITY').getNumberVal(),
value(l).extract('/LINEITEM/PART/@UNITPRICE').getNumberVal()
from XXT_PURCHASEORDER x,
table (xmlsequence(value(x).extract('/PURCHASEORDER/LINEITEMS/LINEITEM'))) l
where existsNode(object_value,'/PURCHASEORDER[REFERENCE="EABEL-
20021009123336251PDT"]') = 1;
select REFERENCE, USERID, SHIPTONAME, SPECIALINSTRUCTIONS
from PURCHASEORDER_TABLE;
select REFERENCE, LINENO, UPC, DESCRIPTION, QUANTITY
from PURCHASEORDER_LINEITEM;
d) XMLSEQUENCE function
It converts an XMLTYPE document into a VARRAY of XMLTYPE elements, which can
then be queried using the TABLE operator just like any other nested collection type. As it
returns a collection, this function can be used in the FROM clause of SQL queries. It can
accept either an XML Type instance or a ref cursor instance.
Syntax: XMLSEQUENCE ([XMLType instance | SYS_REFCURSOR instance])
Case 1: The SQL below uses fixed values (type casted as XML type instance) as input to the
XMLSEQUENCE function.
SELECT value(T).getstringval() Attribute_Value
FROM table(
XMLSequence(
EXTRACT(
XMLType('<Node><ValueNode>Oracle</ValueNode>
<ValueNode>SQL</ValueNode>
<ValueNode>PLSQL</ValueNode></Node>'),
'/Node/ValueNode'))) T ;
Case 2: The SQL below uses a cursor sub query as input to XMLSequence function.
SELECT VALUE(em).getCLOBVal()
AS "XMLTYPE"
FROM table(XMLSequence(Cursor(SELECT * FROM EMP
WHERE EMPNO='5003'))) em ;
e) Extracting element attributes
We can extract the values of attributes of an element by using the @ syntax in XPath, which
specifies that the expression points to an attribute of an element.
SELECT
EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR
T/@QUANTITY') QUANTITY,
EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR
T/@UNITPRICE') UNITPRICE,
EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR
T/@ID') ID
FROM XXT_PURCHASEORDER
WHERE EXISTSNODE(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]')
= 1 ;
f) XML unnesting
If we need to cater for parent elements without child element(s), then we have to use the
correlated FROM "outer join" syntax, which involves placing the Oracle outer join operator,
i.e. (+), on the "child" (i.e. "deficient") component of the FROM clause. In the following
XML, we have two "ADDRESS" parent elements, but only one of them has child "CITY"
elements, but we still need to return both "CITY"s, hence, we need to use the "outer join" :
DECLARE
x XMLTYPE := XMLTYPE.CREATEXML('
<LOCATION>
<ADDRESS>
<PINCODE>184562</PINCODE>
<STATE>
<CITY>
<PINCODE>806745</PINCODE>
</CITY>
<CITY>
<PINCODE>245847</PINCODE>
</CITY>
</STATE>
</ADDRESS>
<ADDRESS>
<PINCODE>244567</PINCODE>
<STATE>
</STATE>
</ADDRESS>
</LOCATION>');
x1 XMLTYPE;
BEGIN
FOR i IN ( SELECT EXTRACTVALUE(VALUE(t), '/ADDRESS/PINCODE') ADDRESS_PINCODE,
EXTRACTVALUE(VALUE(tc),'/CITY/PINCODE') CITY_PINCODE
FROM TABLE(XMLSEQUENCE(x.EXTRACT('LOCATION/ADDRESS'))) t,
TABLE(XMLSEQUENCE(EXTRACT(VALUE(t),'ADDRESS/STATE/CITY'))) (+) tc )
LOOP
dbms_output.put_line('ADDRESS PINCODE : ' || i.ADDRESS_PINCODE || ' : CITY
PINCODE : ' || i.CITY_PINCODE);
END LOOP;
END;
REFERENCES :
1) http://www.oratechinfo.co.uk/sqlxml.html#xpath-post11g
2) http://docs.oracle.com/cd/B12037_01/appdev.101/b10790/xdb04cre.htm
3) http://docs.huihoo.com/oracle/database/11gr1/server.111/b28286/functions240.htm
4) http://docs.oracle.com/cd/E16655_01/appdev.121/e17603/xdb_xquery.htm#CBAHGAJI
5) http://psoug.org/definition/XMLSEQUENCE.htm
6) http://docs.oracle.com/cd/B19306_01/appdev.102/b14259/xdb13gen.htm
7) http://docs.oracle.com/cd/B10501_01/appdev.920/a96621/adx08xsu.htm

More Related Content

PDF
Introduction to Clean Code
PDF
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PDF
Dynamic websites lec3
PDF
The Ring programming language version 1.7 book - Part 35 of 196
PDF
XML Support: Specifications and Development
PPTX
Objective-c Runtime
PDF
Swift for TensorFlow - CoreML Personalization
DOCX
Advance Java Programs skeleton
Introduction to Clean Code
PyCon NZ 2013 - Advanced Methods For Creating Decorators
Dynamic websites lec3
The Ring programming language version 1.7 book - Part 35 of 196
XML Support: Specifications and Development
Objective-c Runtime
Swift for TensorFlow - CoreML Personalization
Advance Java Programs skeleton

What's hot (20)

PDF
PostgreSQL and XML
PPT
Executing Sql Commands
PPTX
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
DOCX
Exercícios Netbeans - Vera Cymbron
PDF
MySQL partitions tutorial
PPT
Blocks In Drupal
PDF
Js 单元测试框架介绍
PDF
Refactoring 메소드 호출의 단순화
PDF
PhpUnit - The most unknown Parts
PDF
Symfony2 and Doctrine2 Integration
PPTX
PHP Traits
PDF
Xml & Java
PDF
spring-tutorial
PDF
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"
PPT
plsql Les08
PDF
Swift internals
PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
PDF
Unittests für Dummies
PDF
Important java programs(collection+file)
PPTX
CodeCamp Iasi 10 march 2012 - Practical Groovy
PostgreSQL and XML
Executing Sql Commands
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
Exercícios Netbeans - Vera Cymbron
MySQL partitions tutorial
Blocks In Drupal
Js 单元测试框架介绍
Refactoring 메소드 호출의 단순화
PhpUnit - The most unknown Parts
Symfony2 and Doctrine2 Integration
PHP Traits
Xml & Java
spring-tutorial
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"
plsql Les08
Swift internals
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
Unittests für Dummies
Important java programs(collection+file)
CodeCamp Iasi 10 march 2012 - Practical Groovy
Ad

Similar to Xml generation and extraction using XMLDB (20)

PPT
DB2 Native XML
PPT
Oracle XML Handling
PPT
Sql2005 Xml
PPTX
Sql2005 xml
PPTX
SQLPASS AD501-M XQuery MRys
PPTX
Xml and databases
PPT
Working With XML in IDS Applications
PDF
Session06 handling xml data
PPT
XMLLec1 (1xML lecturefsfsdfsdfdsfdsfsdfsdfdsf
PPT
XMLLec1.pptsfsfsafasfasdfasfdsadfdsfdf dfdsfds
PPT
XML stands for EXtensible Markup Language
DOCX
Sql server 2008 r2 xml wp
PPTX
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
PPT
PPTX
Unit2_XML_S_SS_US Data_CS19414.pptx
DOC
Creating xml publisher documents with people code
PPT
Xml and DTD's
PPTX
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
PPT
unit_5_XML data integration database management
PDF
SQL/XML on Oracle
DB2 Native XML
Oracle XML Handling
Sql2005 Xml
Sql2005 xml
SQLPASS AD501-M XQuery MRys
Xml and databases
Working With XML in IDS Applications
Session06 handling xml data
XMLLec1 (1xML lecturefsfsdfsdfdsfdsfsdfsdfdsf
XMLLec1.pptsfsfsafasfasdfasfdsadfdsfdf dfdsfds
XML stands for EXtensible Markup Language
Sql server 2008 r2 xml wp
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
Unit2_XML_S_SS_US Data_CS19414.pptx
Creating xml publisher documents with people code
Xml and DTD's
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
unit_5_XML data integration database management
SQL/XML on Oracle
Ad

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Introduction to Artificial Intelligence
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
L1 - Introduction to python Backend.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
System and Network Administration Chapter 2
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Essential Infomation Tech presentation.pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Operating system designcfffgfgggggggvggggggggg
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Odoo POS Development Services by CandidRoot Solutions
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Introduction to Artificial Intelligence
2025 Textile ERP Trends: SAP, Odoo & Oracle
Understanding Forklifts - TECH EHS Solution
L1 - Introduction to python Backend.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Adobe Illustrator 28.6 Crack My Vision of Vector Design
How to Choose the Right IT Partner for Your Business in Malaysia
How Creative Agencies Leverage Project Management Software.pdf
PTS Company Brochure 2025 (1).pdf.......
System and Network Administration Chapter 2
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Essential Infomation Tech presentation.pptx
Upgrade and Innovation Strategies for SAP ERP Customers
VVF-Customer-Presentation2025-Ver1.9.pptx

Xml generation and extraction using XMLDB

  • 1. Generating XML Data from the Database XML data can be generated by following methods.  Generating XML Using Standard SQL/XML Functions.  Generating XML Using Oracle Database SQL Functions.  Generating XML Using DBMS_XMLGEN.  Generating XML Using XSQL Pages Publishing Framework.  Generating XML Using XML SQL Utility (XSU).  Guidelines for Generating XML with Oracle XML DB. 1. Generation of XML Using Standard SQL/XML Functions. i. XMLELEMENT:  Used to construct XML instances from relational data.  Takes element name as argument along with an optional collection of attributes for the element. Syntax: XMLElement(“TagName", column, [xmlAttributes]) Scenario1: To Generate xml containing individual element from a table. select xmlelement("Empno",empno),xmlelement("EmpName",ename) from emp where rownum<3; Scenario2: To Generate an xml containing multiple elements from a table. Select xmlelement( "EmpDetails" , xmlelement ("Empno",empno) , xmlelement("EmpName",ename)) from emp where rownum<3; Scenario3: To Generate a nested xml(Master Detail relationship) containing elements from two tables. Query: select xmlroot(xmlelement("Department", xmlelement("DeptNo",d.deptno) , xmlelement("DeptName",d.dname), xmlelement("Location",d.loc) ,(select xmlelement("Employees",
  • 2. xmlagg(xmlelement("Employee",xmlelement("Empno",e.empno),xmlelement("EmpName" ,e.ename),xmlelement("Position",e.job)))) from emp e where e.deptno = d.deptno) ,xmlcomment('test') ),version '1.0') as result from dept d where d.deptno=20; ii. XMLATTRIBUTES: XMLAttributes is used to specify the values for the attributes of the root element. Function XMLAttributes can be used only in a call to function XMLElement. Syntax: xmlAttributes(column1 as “AttributeName”, column2 as “AttributeName”,…….) Scenario1: select xmlroot(xmlelement("Employee", xmlattributes(empno as "Empno")
  • 3. , xmlelement ("Ename" , ename) , xmlelement ("Salary", sal) ),version '1.0') from emp e where rownum<2; iii. XMLFOREST: XMLForest produces a forest of XMLElements from its arguments. Syntax: XMLForest(column1 [as “AttributeName”] , column2 as [“AttributeName”], ..) XMLForest doesn’t produce empty tags whereas xmlelement does. Eg1: select xmlroot(xmlagg(xmlelement ("Employee",xmlforest( e.EmpNO as "EmpNO" ,e.eNAME as "EmpName" ,e.comm as "Comission" )) ),version '1.0') result from emp e where deptno=30 group by deptno; iv. XMLCONCAT: XMLConcat concatenates all of its arguments to create an XML fragment. Syntax: XMLConcat(XMLType1, XMLType2,…….) Eg1:
  • 4. Before concatenation: select xmlelement("Empno",empno) , xmlelement ("Ename" , ename) , xmlelement ("Salary", sal) from emp e where rownum<3; After Concatenation: select xmlconcat(xmlelement("Empno",empno) , xmlelement ("Ename" , ename) , xmlelement ("Salary", sal)) from emp e where rownum<3; v. XMLAGG: XMLAgg is an aggregate function that produces a forest of XMLElements from a collection of XML elements. Syntax: XMLElement(“TagName”, XMLAgg(XMLType1 order by column ) XMLAgg can also be used to concatenate xmltype instances across rows. Eg1: --Query for generating an xml using xml/sql function xmlagg and order by clause. select xmlroot(xmlelement("Main",xmlagg( xmlelement("Test", xmlcomment ('xmlagg method with order by clause') , xmlelement ("EmpNO",e.empno) , xmlelement ("EmpName",e.ename) , xmlelement ("Job",e.JOB) , xmlelement ("DepartmentNO",e.deptno) ) order by empno ) ),VERSION '1.0' ) as "XMLAGG Order By Example" from emp e where deptno in(10,50);
  • 5. --Query for generating an xml using xml/sql function xmlagg and group by clause. select xmlroot(xmlelement("Main",xmlagg(xmlelement("Test" , xmlcomment ('xmlagg method with group by clause') , xmlelement ("EmpNO",e.empno) , xmlelement ("EmpName",e.ename) , xmlelement ("Job",e.JOB) , xmlelement ("DepartmentNO",e.deptno) ) ) ),VERSION '1.0' ) as testv from emp e group by e.deptno;
  • 6. vi. XMLPI: XMLPI is uesd to generate XML processing instructions.A processing instruction is commonly used to provide to application information that is associated with all or part of an XML document. The application uses the processing instruction to determine how best to process the XML document. Syntax: XMLPI([Name] identifier, ‘ value_expr ‘) select xmlroot(xmlconcat( xmlcomment('Using XMLPI to provide process instructions') ,XMLPI(NAME "xml-stylesheet",'type="text/css" href="test.css"') ,xmlelement("Main",xmlagg(xmlelement("Test", xmlcomment ('xmlagg method with order by clause') , xmlelement ("EmpNO",e.empno) , xmlelement ("EmpName",e.ename) , xmlelement ("Job",e.JOB) , xmlelement ("DepartmentNO",e.deptno) ) order by deptno ) ) ),VERSION '1.0'
  • 7. ) as testv from emp e where deptno=50; The above highlighted part shows the processing instructions that are used to process the xml. vii. XMLCOMMENT: XMLComment is used to generate XML comments. Syntax: xmlcomment(‘expression/comment’) Eg1: select xmlroot(xmlelement("EmpDetails",xmlcomment('Example For XML Comment') ,xmlelement("Empno",empno), xmlelement("EmpName",ename)),version '1.0') from emp where rownum<3; viii. XMLROOT: XMLRoot is used to add a VERSION property, and optionally a STANDALONE property, to the root information item of an XML value. Syntax: XMLRoot(value_expr, version [value_expr],[standalone yes/no[value]]) Eg1: select xmlroot(xmlelement("EmpDetails",xmlelement("Empno",empno), xmlelement("EmpName",ename)), version '1.0') "XMLROOT Example" from emp where rownum<3; ix. XMLSERIALIZE: XMLSerialize is used to obtain a string or a LOB representation of XML data. Default datatype after conversion is CLOB.
  • 8. Syntax: XMLSerialize(document/content value_expr [as datatype]) If type is ‘document’ then the input xml should be well-format single root document otherwise gives error. If ‘content’ the input xml is not validated. Eg1: select xmlserialize(document xmlelement("Empno",empno) as clob) from emp where rownum<3; x. XMLPARSE: XMLParse is used to parse a string containing XML data and generate a corresponding value of XMLType. Syntax: XMLParse(document/content ‘value_expr’ [wellformed]) select XMLParse(document '<Empno>1111</Empno>' WELLFORMED) from emp where rownum<3; 2. Generating XML Using Oracle Database SQL Functions i. XMLCOLATTVAL: XMLColAttVal is used to generate a forest of XML column elements containing the values of the arguments passed in. Syntax: XMLColAttval(column1 [as aliasname],column2 [as aliasname]…..) Eg1: SELECT xmlroot(XMLElement("Emp", XMLAttributes(e.ename AS "FullName" ) , XMLColAttVal (e.hiredate, e.deptno AS "Department") ), version '1.0') AS "RESULT" FROM emp e WHERE e.deptno = 20; <?xml version="1.0"?> <Emp FullName="JONES">
  • 9. <column name="HIREDATE">1981-04-02</column> <column name="Department">20</column> </Emp> ii. XMLCDATA: XMLCDATA is used to generate an XML CDATA section. XMLCDATA will not be parsed by the xmlparser. We can pass some text like javascript containing special characters using XMLCDATA(XML Unparsed character data).The term CDATA is used about text data that should not be parsed by the XML parser.Characters like "<" and "&" are illegal in XML elements."<" will generate an error because the parser interprets it as the start of a new element."&" will generate an error because the parser interprets it as the start of an character entity. Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA. Syntax: xmlcdata(‘ cdata expression ‘) Scenario1: To pass test containing special characters like ‘&’, ‘<’ and ‘@’ select XMLParse(document '<?xml version="1.0"?> <Main> <EmpName>JONES</EmpName> <Testcode>@Test for cdata &a < &b</Testcode> </Main>') "Result" fromdual; The highlighted above tag contains the special symbols like ‘&’ and ‘<’ which causes the error while parsing, as parser interprets
  • 10.  ‘<’ as starting of a newtag.  ‘&’ as starting of a character set. select XMLParse(document '<?xml version="1.0"?> <Main> <EmpName>JONES</EmpName> <![CDATA[@Test for cdata &a &b]]> </Main>') "Result" fromdual; The highlighted above part of xml contains special characters but doesn’t gives error as it is part of ‘cdata’ tag. XML parser doesn’t process the data inside ‘cdata’ tag. iii. SYS_XMLGEN: It takes either a ‘Scalar Value’ or ‘Object Type’, or ‘XMLType’ instance and converts to an XML document. Syntax: SYS_XMLGen(columnname [,fmt]) Eg1: select sys_xmlgen(ename)as "Ename" from emp where deptno=20; Eg2: select sys_xmlgen(sal*2)as "Salary" from emp where deptno=20; Eg3:
  • 11. select sys_xmlgen(sal*2,XMLFormat.createformat('Salary')) as "Salary" from emp where deptno=20; Eg4: query for generating nested xml using sys_xmlgen Step1: create object types for tables that need to be part of xml with corresponding tag names. These may include data columns and also object types. Step2: create a type of object, so that it can be used in creation of another type object. Step3: develop a query to produce the xml using the data type objects created. drop type "DeptXML"; drop type "EmpXML1"; drop type "EmpXML"; / Step1: create or replace type "EmpXML" as object ("EmpNO" number ,"Ename" varchar2(10) ,"DeptNo" number ); / Step2: create or replace type "EmpXML1" as table of "EmpXML"; / Step1: create or replace type "DeptXML" as object ("DeptNO" number, "DeptName" varchar2(14),"Location" varchar2(13),"DeptEmp" "EmpXML1"); / Step3: select sys_xmlgen("DeptXML"( deptno,dname,loc,cast(multiset( select "EmpXML"(e.empno,e.ename,e.deptno) from emp e where e.deptno = d.deptno ) as "EmpXML1" ) ) ,XMLFormat.createFormat('XMLTEST') ) as deptxml from dept d where d.deptno=20;
  • 12. iv. SYS_XMLAGG:SYS_XMLAgg aggregates all XML documents or fragments represented by expr and produce a single XML document. It adds a new enclosing element with a default name, ROWSET. To format the XML document differently, we can use fmt parameter. Syntax: SYS_XMLAgg(columnname [,fmt]) Scenario1: Using sys_xmlagg without using format parameter. select sys_xmlagg(sys_xmlgen(sal*2,XMLFormat.createformat('Salary'))) as "Salary" from emp where deptno=20; As we haven’t specified any format parameter for the sys_xmlagg tag, it adds the default rowset tag to xml formed by aggregating the xml fragments. Eg2: Using sys_xmlagg with using format parameter. select sys_xmlagg(sys_xmlgen(sal*2,XMLFormat.createformat('Salary')),XMLFormat.createfor mat('Employee')) as "Salary" from emp where deptno=20; As we have specified the xmlformat parameter it displays data inside ‘Employee’ tag. 3. Generating XML Using DBMS_XMLGEN: DBMS_XMLGEN package provides various methods to manipulate the xmldata like newcontext(), setrowtag(), setrowsettag(),getxml().getxmltype(),setMaxRows() e.t.c
  • 13. Overview of XML Generation Using DBMS_XMLGEN: The steps are as follows: i. Get the context from the package by supplying a SQL query and calling the newContext() call. ii. Pass the context to all procedures or functions in the package to set the various options. For example, to set the ROW element name, use setRowTag(ctx), where ctx is the context got from the previous newContext() call. iii. Get the XML result, using getXML() or getXMLType(). By setting the maximum number of rows to be retrieved for each fetch using setMaxRows(), you can call either of these functions repeatedly, retrieving up to the maximum number of rows for each call. These functions return XML data (as a CLOB value and as an instance of XMLType, respectively), unless there are no rows retrieved; in that case, these functions return NULL. To determine how many rows were retrieved, use function getNumRowsProcessed(). iv. You can reset the query to start again and repeat step 3. v. Close the closeContext() to free up any resource allocated inside. vi. In conjunction with a SQL query, method DBMS_XMLGEN.getXML() typically returns a result like the following as a CLOB value: Example: Scenario1: Query for generating xml using dbms_xmlgen drop type d1; drop type e2; drop type "EmpDetails"; / create or replace type "EmpDetails" as object( Empno NUMBER(4) ,Empname varchar2(10) ,salary number(7,2) ); / create or replace type e2 as table of "EmpDetails"; / create or replace type d1 as object( deptno number(2) ,deptname varchar2(14) ,location varchar2(13) ,"Employees" e2 ); / select dbms_xmlgen.getxml('select d1( d.deptno ,d.dname ,d.loc ,cast(multiset( select e.empno,e.ename,e.sal from emp e where e.deptno = d.deptno ) as e2 )
  • 14. ) as testxml from dept d' )as result from dual; 4. Generating XML Using XSQL Pages Publishing Framework. The Oracle XSQL Pages publishing framework is an extensible platform for easily publishing XML information in any format you desire. It greatly simplifies combining the power of SQL, XML, and XSLT to publish dynamic web content based on database information. 5. Generating XML Using XML SQL Utility (XSU) Using the XSQL publishing framework, anyone familiar with SQL can create and use declarative templates called "XSQL pages" to:  Assemble dynamic XML "datagrams" based on parameterized SQL queries, and  Transform these "data pages" to produce a final result in any desired XML, HTMLor text-based format using an associated XSLT transformation.
  • 15. XML SQL Utility (XSU) is an XDK component that enables you to transfer XML data through Oracle SQL statements. You can use XSU to perform the following tasks:  Transform data in object-relational database tables or views into XML. XSU can query the database and return the result set as an XML document.  Extract data from an XML document and use canonical mapping to insert the data into a table or a view or update or delete values of the appropriate columns or attributes. 6. Generating XML with Oracle XML DB. Oracle XML DB is a high-performance, native XML storage and retrieval technology that is delivered as a part of all versions of Oracle Database. Oracle XML DB provides full support for all of the key XML standards, including XML, Namespaces, DOM, XQuery, SQL/XML and XSLT. By providing full support for XML standards, Oracle XML DB supports native XML application development. Application developers are able to use XML-centric techniques to store, manage, organize, and manipulate XML content stored in the database. Oracle XML DB also supports the SQL/XML standard, which allows SQL-centric development techniques to be used to publish XML directly from relational data stored in Oracle Database 12c. With Oracle XML DB, you get all the advantages of relational database technology plus all the advantages of the W3C's XML standards.
  • 16. XML ExtractionIn Oracle XML data can be extracted from XMLType columns in the following ways: i) By selecting XMLType columns through SQL(post-11g)  xmltable function  xmlexists function  XMLQuery function  XMLCast function ii) By querying XMLType columns directly(pre-11g)  existsNode() function  extract() function  extractvalue() function  xmlsequence function  Extracting element attributes  XML unnesting i) By selecting XMLType columns through SQL(post-11g) 1) XMLTable function 1. It is an SQL table function that uses XQuery expressions to create relational rows from an XML input document. Its result is queried as a virtual relational table using SQL. It contains one row-generating XQuery expression and, in the COLUMNS clause, one or multiple column-generating expressions. Syntax : XMLTable([XMLnamespaces_clause]'<XQuery>' PASSING <xml column> COLUMNS <new column name> <column type> PATH <XQuery path>)  The XMLNAMESPACES clause contains a set of XML namespace declarations. These declarations are referenced by the XQuery expression, which computes the row, and by the XPath expression in the PATH clause of XML_table_column, which computes the columns for the entire XMLTable function. If we want to use qualified names in the PATH expressions of the COLUMNS clause, then we need to specify the XMLNAMESPACES clause. XMLNAMESPACES ( [ string AS identifier ] [ [, string AS identifier ] ]... [ DEFAULT string ] )
  • 17. XML namespaces are used for providing uniquely named elements and attributes in an XML document. They are defined in a W3C recommendation. An XML instance may contain element or attribute names from more than one XML vocabulary. If each vocabulary is given a namespace, the ambiguity between identically named elements or attributes can be resolved. A namespace name is a uniform resource identifier (URI). Typically, the URI chosen for the namespace of a given XML vocabulary describes a resource under the control of the author or organization defining the vocabulary, such as a URL for the author's Web server. However, the namespace specification does not require nor suggest that the namespace URI be used to retrieve information; it is simply treated by an XML parser as a string.  XQuery is a complete XQuery expression and can include prolog declarations.  The expr in the XML_passing_clause is an expression returning an XMLType or an instance of a SQL scalar datatype that is used as the context for evaluating the XQuery expression. We can specify only one expr in the PASSING clause without an identifier. The result of evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string. PASSING [ BY VALUE ] expr [ AS identifier ] [, expr [ AS identifier ] ]...  The COLUMNS clause is used to transform XML data into relational data. Each of the entries in this clause defines a column with a column name and a SQL data type. The optional COLUMNS clause defines the columns of the virtual table to be created by XMLTable.  If we omit the COLUMNS clause, then XMLTable returns a row with a single XMLType pseudo column named COLUMN_VALUE.  The datatype is required unless XMLTable is used with XML schema-based storage of XMLType, datatype. In this case, if we omit datatype, Oracle XML DB infers the datatype from the XML schema. If the database is unable to determine the proper type for a node, then a default type of VARCHAR2(4000) is used.  FOR ORDINALITY specifies that column is to be a column of generated row numbers. There must be at most one FOR ORDINALITY clause. It is created as a NUMBER column. column { FOR ORDINALITY | datatype [ PATH string ] [ DEFAULT expr ]}  The optional PATH clause specifies that the portion of the XQuery result that is addressed by XQuery expression string is to be used as the column content. If we omit PATH, then the XQuery expression column is assumed. For example: XMLTable(... COLUMNS xyz is equivalent to XMLTable(... COLUMNS xyz PATH 'XYZ')
  • 18. We can use different PATH clauses to split the XQuery result into different virtual-table columns.  The optional DEFAULT clause specifies the value to use when the PATH expression results in an empty sequence. Its expr is an XQuery expression that is evaluated to produce the default value. XMLTable ([ XMLnamespaces_clause , ] '<XQuery>' PASSING <xml column> COLUMNS <new column name> <column type> PATH <XQuery path>) Example: Consider a table XML_TEMP_TABLE which holds some XML data. Below is the create statement this table. CREATE TABLE XML_TEMP_TABLE ( XML_CLOB CLOB ) ; We will use the following XML document : Employee.xml Below INSERT statement add one record having some XML content in it. INSERT INTO XML_TEMP_TABLE VALUES('<?xml version="1.0" encoding="utf- 8"?><Employees xmlns="http://www.w3.org/1999/xml" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Employee EmpNo="5000"><Ename>Test User</Ename><Job>Clerk</Job><Mgr>7698</Mgr><HireDate>04-FEB- 14</HireDate><Sal>12500</Sal><Comm/><Department><DeptNo>50</DeptNo>< Dname/><Address><State>TEXAS</State><City>Dallas</City><Pincode>3412648</ Pincode></Address></Department></Employee><Employee EmpNo="5001"><Ename>Test User1</Ename><Job>MANAGER</Job><Mgr>7839</Mgr><HireDate>09-JUN- 81</HireDate><Sal>30000</Sal><Comm>100</Comm><Department><DeptNo/>< Dname/><Address><State/><City/><Pincode/></Address></Department></Employe e></Employees>'); i) Reading Employee Name, Job, Department Name,City etc. of all employees using XMLTable function. Consider the above XML has xmlns attribute, now we use XMLNAMESPACES function to remove ambiguity between identically named elements/attributes used in different XML vocabulary. SELECT x1.Ename, x1.Job, x1.Mgr, to_date(x1.HireDate,'dd/mm/yyyy') HireDate, x1.Sal, x1.Comm, x2.DeptNo, x2.Dname,
  • 19. x3.State, x3.City, x3.Pincode FROM XML_TEMP_TABLE t , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS Employee XMLTYPE PATH 'Employee')x , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee' PASSING x.Employee COLUMNS Ename VARCHAR2(240) PATH 'Ename' , Job VARCHAR2(240) PATH 'Job' , Mgr NUMBER PATH 'Mgr' , HireDate VARCHAR2(240) PATH 'HireDate' , Sal NUMBER PATH 'Sal' , Comm NUMBER PATH 'Comm', Department XMLTYPE PATH 'Department')x1, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Department' PASSING x1.Department COLUMNS DeptNo NUMBER PATH 'DeptNo', Dname VARCHAR2(240) PATH 'Dname', Address XMLTYPE PATH 'Address') x2, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Address' PASSING x2.Address COLUMNS State VARCHAR2(240) PATH 'State', City VARCHAR2(240) PATH 'City', Pincode NUMBER PATH 'Pincode') x3; The passing clause defines that the xmltype(t.xml_clob) refers to the XML column data of the table XML_TEMP_TABLE of data type xmltype. Employee details can be defined using two different PATH expressions (by using row-generating expression /Employees and Employee ) given above or can be written using single PATH expression (by using row-generating expression /Employees/Employee) given below. All Department details can be defined in different PATH expressions (by using row- generating expression i.e. XQuery as Department, DeptNo, Dname) given above or using single PATH expression (by using XQuery path //Department/DeptNo, //Department/Dname, //Department/Loc) given below. Address details are extracted only in above query(using one more PATH expression State, City, Pincode when we want to extract multilevel XML document): SELECT x.Ename, x.Job, x.Mgr, to_date(x.HireDate,'dd/mm/yyyy') HireDate,
  • 20. x.Sal, x.Comm, x.DeptNo, x.Dname, x.Loc FROM XML_TEMP_TABLE t , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees/Employee' passing xmltype(t.xml_clob) columns Ename VARCHAR2(240) path 'Ename' , Job VARCHAR2(240) path 'Job' , Mgr NUMBER path 'Mgr' , HireDate VARCHAR2(240) path 'HireDate' , Sal NUMBER path 'Sal' , Comm NUMBER path 'Comm', DeptNo NUMBER path '//Department/DeptNo', Dname VARCHAR2(240) path '//Department/Dname', Loc VARCHAR2(240) path '//Department/Loc')x ; ii) Rows with a single XMLType pseudo column named COLUMN_VALUE when columns clause is omitted. SELECT x.* FROM XML_TEMP_TABLE t , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees/Employee' passing xmltype(t.xml_clob) )x ; iii) To retrieve attribute value EmpNo from the xml, @ is used. SELECT x1.EmpNo FROM XML_TEMP_TABLE t ,
  • 21. xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees' passing xmltype(t.xml_clob) columns Employee xmltype path 'Employee')x , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee' passing x.Employee columns EmpNo NUMBER path '@EmpNo') x1; iv) Reading Employee Name of all employees using selection of given current node. SELECT x.Ename FROM XML_TEMP_TABLE t , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees/Employee/Ename' passing xmltype(t.xml_clob) columns Ename VARCHAR2(240) path '.' )x ; v) To fetch the text value of currently selected node item i.e. here Employee Name, select path as /Employee/Ename and then use text() expression to get the value of this selected node. SELECT x1.Ename FROM XML_TEMP_TABLE t , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees' passing xmltype(t.xml_clob) columns Employee xmltype path 'Employee')x , xmltable(xmlnamespaces(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee/Ename' passing x.Employee columns Ename VARCHAR2(240) path 'text()') x1;
  • 22. Along with text() expression, Oracle provides various other useful expressions. For example item(), node(), attribute(), element(), document-node(), namespace(), text(), xs:integer, xs:string. vi)To fetch all employees whose salary is greater than 15000, we can give this condition in XQuery expression. SELECT x1.Ename, x1.Job, x1.Mgr, to_date(x1.HireDate,'dd/mm/yyyy') HireDate, x1.Sal, x1.Comm, x2.DeptNo, x2.Dname, x3.State, x3.City, x3.Pincode FROM XML_TEMP_TABLE t , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS Employee XMLTYPE PATH 'Employee')x , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee[Sal > 15000]' PASSING x.Employee COLUMNS Ename VARCHAR2(240) PATH 'Ename' , Job VARCHAR2(240) PATH 'Job' , Mgr NUMBER PATH 'Mgr' , HireDate VARCHAR2(240) PATH 'HireDate' , Sal NUMBER PATH 'Sal' , Comm NUMBER PATH 'Comm', Department XMLTYPE PATH 'Department')x1, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Department' PASSING x1.Department COLUMNS DeptNo NUMBER PATH 'DeptNo', Dname VARCHAR2(240) PATH 'Dname', Address XMLTYPE PATH 'Address') x2, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Address' PASSING x2.Address COLUMNS State VARCHAR2(240) PATH 'State', City VARCHAR2(240) PATH 'City',
  • 23. Pincode NUMBER PATH 'Pincode') x3; In certain cases, Employees may not have department and address information, then the respective nodes are missing for Department and Address, then to cater parent elements without child elements we have to use the correlated FROM "outer join" syntax, which involves placing the Oracle outer join operator, i.e. (+), on the "child" (i.e. "deficient" i.e. for Department and Address) component of the FROM clause as given below. SELECT x1.Ename, x1.Job, x1.Mgr, to_date(x1.HireDate,'dd/mm/yyyy') HireDate, x1.Sal, x1.Comm, x2.DeptNo, x2.Dname, x3.State, x3.City, x3.Pincode FROM XML_TEMP_TABLE t , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'/Employees' PASSING XMLTYPE(t.xml_clob) COLUMNS Employee XMLTYPE PATH 'Employee')x , XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Employee[Sal > 15000]' PASSING x.Employee COLUMNS Ename VARCHAR2(240) PATH 'Ename' , Job VARCHAR2(240) PATH 'Job' , Mgr NUMBER PATH 'Mgr' , HireDate VARCHAR2(240) PATH 'HireDate' , Sal NUMBER PATH 'Sal' , Comm NUMBER PATH 'Comm', Department XMLTYPE PATH 'Department')x1, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Department' PASSING x1.Department COLUMNS DeptNo NUMBER PATH 'DeptNo', Dname VARCHAR2(240) PATH 'Dname', Address XMLTYPE PATH 'Address') (+) x2, XMLTABLE(XMLNAMESPACES(DEFAULT 'http://www.w3.org/1999/xml') ,'Address' PASSING x2.Address COLUMNS State VARCHAR2(240) PATH 'State', City VARCHAR2(240) PATH 'City', Pincode NUMBER PATH 'Pincode')(+) x3;
  • 24. vii) Usage of Xpath syntax. We will use the following XML document in the examples below. bookstore.xml Selecting Nodes : XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below: Expression Description nodename Selects all nodes with the name “nodename” / Selects from the root node // Selects nodes in the document from the current node that match the selection no matter where they are . Selects the current node .. Selects the parent of the current node @ Selects attributes In the table below we have listed some path expressions and the result of the expressions: Path Expression Result Bookstore Selects all nodes with the name “bookstore” /bookstore Selects the root element bookstore Note: If the path starts with a slash ( / ) it always represents an absolute path to an element! Bookstore/book Selects all book elements that are children of bookstore //book Selects all book elements no matter where they are in the document bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element //@lang Selects all attributes that are named lang Predicates : Predicates are used to find a specific node or a node that contains a specific value embedded in square brackets. In the table below we have listed some path expressions with predicates and the result of the expressions: Path Expression Result /bookstore/book[1] Selects the first book element that is the child of the bookstore element. Note: In IE 5,6,7,8,9 first node is[0], but
  • 25. according to W3C, it is [1]. To solve this problem in IE, set the SelectionLanguage to XPath: In JavaScript: xml.setProperty("SelectionLanguage","XPath"); /bookstore/book[last()] Selects the last book element that is the child of the bookstore element /bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element /bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element //title[@lang] Selects all the title elements that have an attribute named lang //title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng' /bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00 /bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00 Selecting Unknown Nodes : XPath wildcards can be used to select unknown XML elements. Wildcard Description * Matches any element node @* Matches any attribute node node() Matches any node of any kind In the table below we have listed some path expressions and the result of the expressions: Path Expression Result /bookstore/* Selects all the child nodes of the bookstore element //* Selects all elements in the document //title[@*] Selects all title elements which have any attribute Selecting Several Paths : By using the | operator in an XPath expression we can select several paths. In the table below we have listed some path expressions and the result of the expressions: Path Expression Result //book/title | //book/price Selects all the title AND price elements of all book elements //title | //price Selects all the title AND price elements in the
  • 26. document /bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price elements in the document 2) XMLEXISTS function It is an SQL function that can be used wherever a BOOLEAN datatype can be used, such as in predicate or in a CASE statement. It is used to determine if a given XML node exists in an XML document. The functional equivalent of this prior to the appearance of this function was either the EXISTSNODE function, but EXISTSNODE returns a numeric 1 or 0, not a BOOLEAN, or to do the check via XPath in XMLTABLE (or via EXTRACT). The use of XMLExists is limited to a SQL WHERE clause or CASE expression. If we need to use XMLExists in a SELECT list, then we wrap it in a CASE expression: CASE WHEN XMLExists(...) THEN 'TRUE' ELSE 'FALSE' END Syntax : XMLEXISTS(<xpath/xquery> PASSING <xmltype document>) e.g. assuming that table XXT_PURCHASEORDER has an XMLTYPE column SELECT OBJECT_VALUE FROM XXT_PURCHASEORDER WHERE XMLExists('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]' PASSING OBJECT_VALUE); SELECT CASE WHEN XMLEXISTS('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]' PASSING XP.OBJECT_VALUE) THEN 'TRUE' ELSE 'FALSE' END "CASE_RESULT" FROM XXT_PURCHASEORDER XP; 3) XMLQuery Function We use XMLQuery function to construct or query XML data. This function takes as arguments an XQuery expression, as a string literal, and an optional XQuery context item, as a
  • 27. SQL expression. The context item establishes the XPath context in which the XQuery expression is evaluated. Additionally, XMLQuery accepts as arguments any number of SQL expressions whose values are bound to XQuery variables during the XQuery expression evaluation. The function returns the result of evaluating the XQuery expression, as an XMLType instance. Syntax : XMLQUERY ( XQuery_string [ XML_passing_clause ] RETURNING CONTENT [ NULL ON EMPTY ])  XQuery_string is a complete XQuery expression, possibly including a prolog, as a literal string.  The XML_passing_clause is the keyword PASSING followed by one or more SQL expressions (expr) that each return an XMLType instance or an instance of a SQL scalar data type (that is, not an object or collection data type). Each expression (expr) can be a table or view column value, a PL/SQL variable, or a bind variable with proper casting. All but possibly one of the expressions must each be followed by the keyword AS and an XQuery identifier. The result of evaluating each expr is bound to the corresponding identifier for the evaluation of XQuery_string. If there is an expr that is not followed by an AS clause, then the result of evaluating that expr is used as the context item for evaluating XQuery_string  RETURNING CONTENT indicates that the value returned by an application of XMLQuery is an instance of parameterized XML type XML(CONTENT), not parameterized type XML(SEQUENCE). It is a document fragment that conforms to the extended Infoset data model. As such, it is a single document node with any number of children. The children can each be of any XML node type; in particular, they can be text nodes. 4) XMLCast Function XMLCast function casts its first argument to the scalar SQL data type specified by its second argument. The first argument is a SQL expression that is evaluated. Any of the following SQL data types can be used as the second argument:  NUMBER  VARCHAR2  CHAR  CLOB  BLOB  REF XMLTYPE  any SQL date or time data type Syntax: XMLCAST ( value_expression AS datatype ) The result of evaluating the first XMLCast argument is an XML value. It is converted to the target SQL data type by using the XQuery atomization process and then casting the XQuery
  • 28. atomic values to the target data type. If this conversion fails, then an error is raised. If conversion succeeds, the result returned is an instance of the target data type. Below example extracts the scalar value of XML Fragment (i.e. node REFERENCE) Using XMLCast and XMLQuery functions. SELECT XMLCast(XMLQuery('/PURCHASEORDER/REFERENCE' PASSING OBJECT_VALUE RETURNING CONTENT) AS VARCHAR2(100)) "REFERENCE" FROM XXT_PURCHASEORDER WHERE XMLExists('/PURCHASEORDER[INSTRUCTIONS="Air Mail"]' PASSING OBJECT_VALUE); ii)We By querying XMLType columns directly a) existsNode() function Syntax : existsNode(XMLType_instance IN XMLType, XPath_string IN VARCHAR2, namespace_string IN varchar2 := null) RETURN NUMBER The existsNode() XMLType function checks if the given XPath evaluation results in at least a single XML element or text node. If so, it returns the numeric value 1, otherwise, it returns a 0. The namespace parameter can be used to identify the mapping of prefix(es) specified in the XPath_string to the corresponding namespace(s). Using existsNode() on XMLType The following example demonstrates how to use existsNode() on an XMLType instance in a query. CREATE TABLE XXT_PURCHASEORDER OF XMLType; / INSERT INTO XXT_PURCHASEORDER VALUES ('<PURCHASEORDER xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:8080/source/schemas/poSource/xsd/purc haseOrder.xsd"><REFERENCE>SBELL- 2002100912333601PDT</REFERENCE><ACTIONS><ACTION><USER>SVOLLMAN</ USER></ACTION></ACTIONS><REJECT/><REQUESTOR>Sarah J. Bell</REQUESTOR><USER>SBELL</USER><COSTCENTER>S30</COSTCENTER><S HIPPINGINSTRUCTIONS><NAME>Sarah J. Bell</NAME><ADDRESS>400 Oracle
  • 29. Parkway Redwood Shores CA 94065 USA</ADDRESS><TELEPHONE>650 506 7400</TELEPHONE></SHIPPINGINSTRUCTIONS><INSTRUCTIONS>Air Mail</INSTRUCTIONS><LINEITEMS><LINEITEM ITEMNUMBER="1"><DESCRIPTION>A Night to Remember</DESCRIPTION><PART ID="715515009058" UNITPRICE="39.95" QUANTITY="2"/></LINEITEM><LINEITEM ITEMNUMBER="2"><DESCRIPTION>The Unbearable Lightness Of Being</DESCRIPTION><PART ID="37429140222" UNITPRICE="29.95" QUANTITY="2"/></LINEITEM><LINEITEM ITEMNUMBER="3"><DESCRIPTION>Sisters</DESCRIPTION><PART ID="715515011020" UNITPRICE="29.95" QUANTITY="4"/></LINEITEM></LINEITEMS></PURCHASEORDER>'); SELECT extract(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE" FROM XXT_PURCHASEORDER WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1; An XPath expression such as /PURCHASEORDER/REFERENCE results in a single node. Therefore, existsNode() will return 1 for that XPath whereas /PURCHASEORDER/REFERENCE/text(),results in a single text node. An XPath expression such as /PO/POTYPE does not return any nodes. Therefore, an existsNode() on this would return the value 0.It can be used in queries in the WHERE but never in the SELECT list and to create function-based indexes to speed up evaluation of queries. The following example uses existsNode() to select rows/find a node with INSTRUCTIONS set to Air Mail. SELECT object_value FROM XXT_PURCHASEORDER WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1; Using Indexes to Evaluate existsNode() We can create function-based indexes using existsNode() to speed up the execution. We can also create a CTXXPATH index to help speed up arbitrary XPath searching. b) extract() function The extract() XMLType function is similar to the existsNode() function. It applies a VARCHAR2 XPath string with an optional namespace parameter and returns an XMLType instance containing an XML fragment. Syntax:
  • 30. extract(XMLType_instance IN XMLType, XPath_string IN VARCHAR2, namespace_string In varchar2 := null) RETURN XMLType; extract() on XMLType extracts the node or a set of nodes from the document identified by the XPath expression. The extracted nodes can be elements, attributes, or text nodes. If multiple text nodes are referenced in the XPath, the text nodes are collapsed into a single text node value. Namespace can be used to supply namespace information for prefixes in the XPath string. The XMLType resulting from applying an XPath through extract() need not be a well-formed XML document but can contain a set of nodes or simple scalar data. We can use the getStringVal() or getNumberVal() methods on XMLType to extract the scalar data. A text node is considered an XMLType. In other words, extract(object_value, '/PURCHASEORDER/REFERENCE/text()') still returns an XMLtype instance although the instance may actually contain only text. We can use getStringVal() to get the text value out as a VARCHAR2 result. To identify text nodes in elements, text() node test function is used before using the getStringVal() or getNumberVal() to convert them to SQL data or else it produces an XML fragment. For example, XPath expressions:  /PURCHASEORDER/REFERENCE identifies the fragment <REFERENCE>...</ REFERENCE >  /PURCHASEORDER/REFERENCE/text() identifies the value of the text node of the Reference element. We can use the index mechanism to identify individual elements in case of repeated elements in an XML document. For example, if we have an XML document such as: PURCHASEORDER.x ml then we can use:  // LINEITEM [1] to identify the first LineItem element.  // LINEITEM [2] to identify the second LineItem element. The result of extract() is always an XMLType. If applying the XPath produces an empty set, then extract() returns a NULL value.Hence it’s used to extract:  Numerical values on which function-based indexes can be created to speed up processing  Collection expressions for use in the FROM clause of SQL statements  Fragments for later aggregation to produce different documents The following example uses extract() to query the value of the REFERENCE column or Node for orders with INSTRUCTIONS set to Air Mail. SELECT extract(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE" FROM XXT_PURCHASEORDER
  • 31. WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1; Functions extract().getStringVal() and extractValue() differ in their treatment of entity encoding. Function extractValue() unescapes any encoded entities; extract().getStringVal() returns the data with entity encoding intact. c) extractValue() Function The extractvalue() XMLType function takes as arguments an XMLType instance and an XPath expression. It returns a scalar value corresponding to the result of the XPath evaluation on the XMLType instance.  XML schema-based documents. For documents based on XML schema, if Oracle Database can infer the type of the return value, then a scalar value of the appropriate type is returned. Otherwise, the result is of type VARCHAR2.  Non- schema-based documents. If the extractValue() query can potentially be re-written, such as when the query is over a SQL/XML view, then a scalar value of the appropriate type is returned. Otherwise, the result is of type VARCHAR2. The extractValue() function attempts to determine the proper return type from the XML schema of the document, or from other information such as the SQL/XML view else returns a VARCHAR2. With XML schema-based content, extractValue() returns the underlying datatype in most cases. For CLOB datatypes, it will return the CLOB directly. If a specific datatype is desired, conversion functions such as to_char or to_date can be put around the extractValue() function call or around an extract.getStringVal(). This can help maintain consistency between different queries regardless of whether the queries can be rewritten. Syntax : EXTRACTVALUE ( XMLType_instance, XPath_string [, namespace_string] ) A Shortcut Function extractValue() permits us to extract the desired value more easily than when using the equivalent extract() function. It is an ease-of-use and shortcut function. So instead of using: extract(x,'path/text()').get(string|number)val() we can replace extract().getStringVal() or extract().getnumberval() with extractValue() as follows: extractValue(x, 'path/text()') With extractValue() we can leave off the text(), but ONLY if the node pointed to by the 'path' part has only one child and that child is a text node. Otherwise, an error is thrown.extractValue() has the same syntax as extract(). extractValue() Characteristics  It always returns only scalar content, such as NUMBER, VARCHAR2, and so on.  It cannot return XML nodes or mixed content. It raises an error at compile or run time if it gets XML nodes as the result.  It always returns VARCHAR2 by default. If the node value is bigger than 4K, a runtime error occurs.
  • 32.  In the presence of XML schema information, at compile time, extractValue() can automatically return the appropriate datatype based on the XML schema information, if it can detect so at compile time of the query. For instance, if the XML schema information for the path /PO/POID indicates that this is a numerical value, then extractValue() returns a NUMBER.  If the extractValue() is on top of a SQL/XML view and the type can be determined at compile time, the appropriate type is returned.  If the XPath identifies a node, then it automatically gets the scalar content from its text child. The node must have exactly one text child. For example: extractValue(xmlinstance, ' /PURCHASEORDER/REFERENCE’) extracts out the text child of Reference. This is equivalent to: extract(xmlinstance, ' /PURCHASEORDER/REFERENCE/text()').getstringval() Below query extracts the scalar value of the REFERENCE column/ XML Fragment using extractValue() function. This is in contrast to the extract() function where the entire <REFERENCE> element is extracted. SELECT extractValue(object_value,'/PURCHASEORDER/REFERENCE') "REFERENCE" FROM XXT_PURCHASEORDER WHERE existsNode(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1; Functions extract().getStringVal() and extractValue() differ in their treatment of entity encoding. Function extractValue() unescapes any encoded entities; extract().getStringVal() returns the data with entity encoding intact. Querying XML Data With SQL Below performs a query of data(XMLType) in given rows using extractValue() and existsNode() SELECT extractValue(object_value,'/PURCHASEORDER/REFERENCE') REFERENCE, extractValue(object_value,'/PURCHASEORDER/*//USER') USERID, case when existsNode(object_value,'/PURCHASEORDER/LINEITEMS/LINEITEM[DESCRIPT ION="A Night to Remember"]') = 1 then 'Accepted' else 'Rejected' end "STATUS", extractValue(object_value,'//COSTCENTER') COSTCENTER FROM XXT_PURCHASEORDER WHERE existsNode(object_value,'//COSTCENTER') = 1 ORDER By extractValue(object_value,'//REFERENCE');
  • 33. Below example demonstrates using a cursor in PL/SQL to query XML data. A local XMLType instance is used to store transient data. declare xNode XMLType; vText VARCHAR2(256); vReference VARCHAR2(32); cursor getPurchaseOrder (REFERENCE in VARCHAR2) is SELECT object_value XML FROM XXT_PURCHASEORDER WHERE EXISTSNODE(object_value,'/PURCHASEORDER[REFERENCE="'|| REFERENCE || '"]') = 1; begin vReference := 'SBELL-2002100912333601PDT'; FOR c IN getPurchaseOrder(vReference) LOOP xNode := c.XML.extract('//REQUESTOR'); vText := xNode.extract('//text()').getStringVal(); dbms_output.put_line(' The Requestor for Reference ' || vReference || ' is '|| vText); END LOOP; vReference := 'SBELL-2002100912333601PDT'; FOR c IN getPurchaseOrder(vReference) LOOP xNode := c.XML.extract('//LINEITEM[@ITEMNUMBER="1"]/DESCRIPTION'); vText := xNode.extract('//text()').getStringVal(); dbms_output.put_line(' The Description of LineItem[1] for Reference ' || vReference || ' is '|| vText); END LOOP; end; Below example shows how to extract data from an XML purchase order and insert it into a SQL relational table using the extract() function. create table PURCHASEORDER_TABLE(
  • 34. REFERENCE VARCHAR2(28) PRIMARY KEY, REQUESTER VARCHAR2(48), ACTIONS XMLTYPE, USERID VARCHAR2(32), COSTCENTER VARCHAR2(3), SHIPTONAME VARCHAR2(48), ADDRESS VARCHAR2(512), PHONE VARCHAR2(32), SPECIALINSTRUCTIONS VARCHAR2(2048) ); create table PURCHASEORDER_LINEITEM( REFERENCE, FOREIGN KEY ("REFERENCE") REFERENCES "PURCHASEORDER_TABLE" ("REFERENCE") ON DELETE CASCADE, LINENO NUMBER(10), PRIMARY KEY ("REFERENCE","LINENO"), UPC VARCHAR2(14), DESCRIPTION VARCHAR2(128), QUANTITY NUMBER(10), UNITPRICE NUMBER(12,2) ); insert into PURCHASEORDER_TABLE( REFERENCE, REQUESTER, ACTIONS, USERID, COSTCENTER, SHIPTONAME, ADDRESS, PHONE, SPECIALINSTRUCTIONS) select x.object_value.extract('/PURCHASEORDER/REFERENCE/text()').getStringVal(), x.object_value.extract('/PURCHASEORDER/REQUESTOR/text()').getStringVal(), x.object_value.extract('/PURCHASEORDER/ACTIONS'), x.object_value.extract('/PURCHASEORDER/USER/text()').getStringVal(), x.object_value.extract('/PURCHASEORDER/COSTCENTER/text()').getStringVal(), x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/NAME/text()').getSt ringVal(), x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/ADDRESS/text()').g etStringVal(), x.object_value.extract('/PURCHASEORDER/SHIPPINGINSTRUCTIONS/TELEPHONE/text( )').getStringVal(), x.object_value.extract('/PURCHASEORDER/INSTRUCTIONS/text()').getStringVal() from XXT_PURCHASEORDER x
  • 35. where x.object_value.existsNode('/PURCHASEORDER[REFERENCE="SBELL- 2002100912333601PDT"]') = 1; insert into PURCHASEORDER_LINEITEM( REFERENCE, LINENO, UPC, DESCRIPTION, QUANTITY, UNITPRICE) select x.object_value.extract('/PURCHASEORDER/REFERENCE/text()').getStringVal(), value(l).extract('/LINEITEM/@ITEMNUMBER').getNumberVal(), value(l).extract('/LINEITEM/PART/@ID').getNumberVal(), value(l).extract('/LINEITEM/DESCRIPTION/text()').getStringVal(), value(l).extract('/LINEITEM/PART/@QUANTITY').getNumberVal(), value(l).extract('/LINEITEM/PART/@UNITPRICE').getNumberVal() from XXT_PURCHASEORDER x, table (xmlsequence(value(x).extract('/PURCHASEORDER/LINEITEMS/LINEITEM'))) l where existsNode(object_value,'/PURCHASEORDER[REFERENCE="EABEL- 20021009123336251PDT"]') = 1; select REFERENCE, USERID, SHIPTONAME, SPECIALINSTRUCTIONS from PURCHASEORDER_TABLE; select REFERENCE, LINENO, UPC, DESCRIPTION, QUANTITY from PURCHASEORDER_LINEITEM; d) XMLSEQUENCE function It converts an XMLTYPE document into a VARRAY of XMLTYPE elements, which can then be queried using the TABLE operator just like any other nested collection type. As it returns a collection, this function can be used in the FROM clause of SQL queries. It can accept either an XML Type instance or a ref cursor instance.
  • 36. Syntax: XMLSEQUENCE ([XMLType instance | SYS_REFCURSOR instance]) Case 1: The SQL below uses fixed values (type casted as XML type instance) as input to the XMLSEQUENCE function. SELECT value(T).getstringval() Attribute_Value FROM table( XMLSequence( EXTRACT( XMLType('<Node><ValueNode>Oracle</ValueNode> <ValueNode>SQL</ValueNode> <ValueNode>PLSQL</ValueNode></Node>'), '/Node/ValueNode'))) T ; Case 2: The SQL below uses a cursor sub query as input to XMLSequence function. SELECT VALUE(em).getCLOBVal() AS "XMLTYPE" FROM table(XMLSequence(Cursor(SELECT * FROM EMP WHERE EMPNO='5003'))) em ; e) Extracting element attributes We can extract the values of attributes of an element by using the @ syntax in XPath, which specifies that the expression points to an attribute of an element. SELECT EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR T/@QUANTITY') QUANTITY, EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR T/@UNITPRICE') UNITPRICE,
  • 37. EXTRACTVALUE(OBJECT_VALUE,'/PURCHASEORDER/LINEITEMS/LINEITEM[1]/PAR T/@ID') ID FROM XXT_PURCHASEORDER WHERE EXISTSNODE(object_value,'/PURCHASEORDER[INSTRUCTIONS="Air Mail"]') = 1 ; f) XML unnesting If we need to cater for parent elements without child element(s), then we have to use the correlated FROM "outer join" syntax, which involves placing the Oracle outer join operator, i.e. (+), on the "child" (i.e. "deficient") component of the FROM clause. In the following XML, we have two "ADDRESS" parent elements, but only one of them has child "CITY" elements, but we still need to return both "CITY"s, hence, we need to use the "outer join" : DECLARE x XMLTYPE := XMLTYPE.CREATEXML(' <LOCATION> <ADDRESS> <PINCODE>184562</PINCODE> <STATE> <CITY> <PINCODE>806745</PINCODE> </CITY> <CITY> <PINCODE>245847</PINCODE> </CITY> </STATE> </ADDRESS> <ADDRESS> <PINCODE>244567</PINCODE> <STATE> </STATE> </ADDRESS> </LOCATION>'); x1 XMLTYPE; BEGIN FOR i IN ( SELECT EXTRACTVALUE(VALUE(t), '/ADDRESS/PINCODE') ADDRESS_PINCODE, EXTRACTVALUE(VALUE(tc),'/CITY/PINCODE') CITY_PINCODE FROM TABLE(XMLSEQUENCE(x.EXTRACT('LOCATION/ADDRESS'))) t, TABLE(XMLSEQUENCE(EXTRACT(VALUE(t),'ADDRESS/STATE/CITY'))) (+) tc ) LOOP dbms_output.put_line('ADDRESS PINCODE : ' || i.ADDRESS_PINCODE || ' : CITY PINCODE : ' || i.CITY_PINCODE); END LOOP; END;
  • 38. REFERENCES : 1) http://www.oratechinfo.co.uk/sqlxml.html#xpath-post11g 2) http://docs.oracle.com/cd/B12037_01/appdev.101/b10790/xdb04cre.htm 3) http://docs.huihoo.com/oracle/database/11gr1/server.111/b28286/functions240.htm 4) http://docs.oracle.com/cd/E16655_01/appdev.121/e17603/xdb_xquery.htm#CBAHGAJI 5) http://psoug.org/definition/XMLSEQUENCE.htm 6) http://docs.oracle.com/cd/B19306_01/appdev.102/b14259/xdb13gen.htm 7) http://docs.oracle.com/cd/B10501_01/appdev.920/a96621/adx08xsu.htm