XML Functionalities in Oracle. An overview of implementation and... | by Gaurav Goel | Towards Data Science

There is always an extensive demand for exchanging data between different sources without worrying about how the receiver will use it or how it will be displayed. XML does that thing for us. It’s a W3C(World Wide Web Consortium) initiative that allows information to be encoded in meaningful structure and rules that humans and machines can understand easily.
XML stands for eXtensible Markup Language. XML is not a replacement of HTML.
While HTML is designed with focus on how to ‘display’ data, XML is designed how to ‘store’ and ‘transport’ it.
XML, in itself, does not DO anything.
Let’s look at a sample xml document:
<message><to>Tom</to><from>Bill</from><body>Send me your phone number</body></message>
The above XML document contains a message with a body having a sender and receiver information. But it does not do anything on its own. It has just structured and stored information. Someone has to write a software code to receive, send or display it.
The tags like <from> or <to> are not predefined. They are written by the author of this XML document.
Thus, in short, we can say that XML is a software and hardware independent tool or way to structure, store and carry information.
An XML document has a tree structure that starts at the “root” element. An example is as follows:
<?xml version=”1.0"?><Employees><Empl id=”1"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees><Employees><Empl id=”1"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees>
The first line is the XML declaration. It defines the XML version. The next line declared the “root” element of this XML document. So, “Employees” is root element here. The other elements like “Empl”, “FirstName”, “lastName” and “Dept” are the child elements. Inside EMPL element, there is field id with value”1”. It is called attribute of that element. Attributes provide additional information about elements. Attribute values are always enclosed in quotes(single or double). A XML document with correct syntax is called “well-formed” XML.
A Document Type definition (DTD) defines the legal building blocks of an XML document. It defines a document structure with a list of legal elements and attributes. A DTD document example is as follows:
<?xml version=”1.0"?> <!DOCTYPE message [  <!ELEMENT message (to,from,body)> <!ELEMENT to (#PCDATA)>  <!ELEMENT from (#PCDATA)>  <!ELEMENT body (#PCDATA)> ]>
The DTD above is interpreted like this: The DTD above is interpreted like this:
!DOCTYPE note defines that the root element of this document is message.!ELEMENT note defines that the note element contains four elements: “to,from,body”.!ELEMENT to defines the to element to be of the type “#PCDATA”.!ELEMENT from defines the from element to be of the type “#PCDATA”.!ELEMENT body defines the body element to be of the type “#PCDATA”.
The description (#PCDATA) specifies parsed character data. Parsed data is the text between the start tag and the end tag of an XML element. Parsed character data is text without child elements.
An XML Schema Definition(XSD) document is an XML based alternative to DTD.
A “Valid” XML document is a “well-formed” XML document which also conforms to the rules of DTD or XSD.
As discussed, HTML tags are predefined. In HTML <table> defines a table and a browser already knows how to display it. However, in XML <table> can mean anything. XML is focused on structuring and storing the data. So, we need a mechanism to define how this data should be displayed in browsers, cellphones etc. XSL (eXtensible Style Language) is the language to do that. It defines the rules to interpret the elements of the XML document.
Let's take an XML document “CDCatalog.xml” defined as follows:
<?xml version=”1.0" encoding=”ISO-8859–1"?><?xml-stylesheet type=”text/xsl” href=”DisplayCD.xsl”?><catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd></catalog>
In the second line, it's referring to an XSL document DisplayCD.xsl This document can be defined as below:
<?xml version=”1.0" encoding=”ISO-8859–1"?><xsl:stylesheet version=”1.0" xmlns:xsl=”http://www.w3.org/1999/XSL/Transform"><xsl:template match=”/”> <html> <body> <h2>Title</h2><xsl:for-each select=”catalog/cd”> <xsl:value-of select=”title”/> <br/></xsl:for-each> </body> </html></xsl:template></xsl:stylesheet>
Let's understand DisplayCD.xsl , line by line.
The first line <?xml version=”1.0" encoding=”ISO-8859–1"?>, defines the XML version and encoding used.
The next line declared the XSL version and Namespace to be used. The xmlns:xsl=”http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT namespace.
The <xsl:template> element defines a template. The match=”/” attribute associates the template with the root of the XML source document.
The content inside the <xsl:template> element defines some HTML to write to the output.
The <xsl:value-of> element can be used to extract the value of an XML element. The select attribute in the example above, contains an XPath expression. An XPath expression works like navigating a file system; a forward slash (/) selects subdirectories. The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set.
When CDCatalog.xml is opened in a web browser, it will display the data as follows, as defined in DisplayCD.xsl:
Oracle uses a new datatype, XML Type, to facilitate handling of XML data in the database. To view the data of an existing table in XML format, you can write the query as follows:
select XMLTYPE(cursor(select * from dept)) XML_Data from dual
The output will be as follows:
XML_Data==============<?xml version=”1.0"?><ROWSET> <ROW> <DEPTID>10</DEPTID> <DEPTNAME>ACCOUNTING</DEPTNAME> <LOC>NEW YORK</LOC> </ROW> <ROW> <DEPTID>20</DEPTID> <DEPTNAME>RESEARCH</DEPTNAME> <LOC>DALLAS</LOC> </ROW> <ROW> <DEPTID>30</DEPTID> <DEPTNAME>SALES</DEPTNAME> <LOC>CHICAGO</LOC> </ROW> <ROW> <DEPTID>40</DEPTID> <DEPTNAME>OPERATIONS</DEPTNAME> <LOC>BOSTON</LOC> </ROW></ROWSET>
XMLType can accept a Ref Cursor as a parameter
To insert the contents of an XML file into an Oracle table, follow the below steps:
Create a table of type XMLTYPE e.g create table catalog of xmltypeCreate an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g:
Create a table of type XMLTYPE e.g create table catalog of xmltype
Create an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g:
CREATE OR REPLACE DIRECTORY MYXMLDIR AS ‘D:\Gaurav\Trainings\Files’;
3. Execute the insert statement as follows:
INSERT INTO catalog VALUES(XMLType(bfilename(‘MYXMLDIR’,’CDCatalog.xml’),nls_charset_id(‘AL32UTF8’)));
The value passed to nls_charset_id indicates that the encoding for the file to be read is UTF-8.
4. This value can be selected using OBJECT_VALUE e.g
select OBJECT_VALUE from catalog
XMLELEMENT is a function that returns an XML Type. It accepts 2 arguments: the first argument is the name of the tag, the second argument is the value and could be string,XMLTYPE, number or a date.
select empno, ename from emp where ename like ‘F%’;
This will return the employee number and name of the employee whose name contains letter ‘S’ as follows:
Using XMLELEMENT, we can add xmltype with a userdefined tag name and value as employee name e.g
select empno, xmlelement(name,ename) namefromempwhere ename like ‘%S%’;
It generates an XMLType with tag NAME and the employee name as value:
XMLELEMENT can be nested and can contain attributes:
select empno, xmlelement(                         emp,                         xmlattributes (empno, deptno),                          xmlelement(name, ename),                         xmlelement(job,job)                         emp                         )                 from                 emp                 where ename like '%S%'
EXTRACT and EXTRACTVALUE:
The EXTRACT function takes 2 arguments: an XMLTYPE element and an XPATH string and returns an XMLTYPE instance e.g
To select that data where country=”USA”, following query will be used on “catalog” table.
select extract(OBJECT_VALUE,’/catalog/cd[country =”USA”]’) cd_usafromcatalog
EXTRACTVALUE is used to extract the particular value under a node. E.g if we have to find the artist name where title=’Still got the blues’, the query will be written as below:
select extractvalue(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]//artist/text()’) artist_namefromcatalog
The output:
EXISTSNODE:
EXISTSNODE checks the existence of an XPATH expression e.g if we want to know that whether the title “Still got the blues” is present in catalog or not, we can write the query as follows:
select existsnode(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]’) exist_flgfromcatalog
The output 1 indicates that it exists while 0 indicates that it is not present.
XMLAGG:
XMLAGG is used to aggregate multiple rows in a single XML document. E.g to aggregate employees in each department, the query can be written as:
selectxmlelement(emp,xmlagg(xmlelement(dept, xmlagg( xmlelement(name,ename) order by ename ) ) )  )  from empgroup by empno
UPDATEXML:
UPDATEXML searches for an XPATH expression and updates it. E.g
UPDATE catalog SET object_value = UPDATEXML(object_value, ‘/catalog/cd/title/text()’,’changed’)
This will update all the titles to “changed” in the table catalog.
This article was aimed to give the reader, a basic understanding of XML and related technologies and how XML data is handled in Oracle database. For more detailed knowledge of XML capabilities of Oracle, please refer to the below link: