Sunday, August 6, 2017

Parse XML in Oracle Using EXTRACTVALUE and XMLTABLE

9:19 AM


                There are Multiple ways to parse XML in Oracle but in this post i will show how to parse using EXTRACTVALUE and  XMLTABLE.  Let's Suppose you have an following  XML stored  in a column MSG in table TMP.


<students>
   <student id='123'>
             <name>Ram</name>
     <marks>100</marks>
   </student>
</students>

EXTRACTVALUE 

             Now if you want to extract <name> value, you will use a function like below.


select
EXTRACTVALUE(XMLTYPE(MSG),'/students/student/name')
from TMP;


                            Above function takes MSG ( XML source ) in XMLTYPE format.( Since my MSG column is varchar i converted to XMLTYPE ) and returns the value specified in path (XPATH). I have specified absolute path here,you can also specify relative path using //name. 

                           See the following video for more detailed explanation on EXTRACVALUE and XMLTABLE 


XMLTABLE


                             EXTRACTVALUE can return only one single value. If you want to render XML as table structure like rows and columns you have to use XMLTABLE. It will create virtual table based on specification. Syntax for XMLTABLE table is as below.


select students.* from TMP,XMLTABLE(
'/students/student'
PASSING XMLTYPE(MSG)
COLUMNS
"id" NUMBER PATH '@id',
"name" VARCHAR2(20)  PATH 'name',
"marks"  NUMBER PATH 'marks'
) students;

   In above query '/students/student' is row specifier XPATH, meaning now of student tags=no of rows.  Under each Student element  id,name and marks are columns. 

                    Advantage of XMLTABLE is that it can dynamically return all the rows whereas EXTARCTVALUE can only return single row.

      






Written by

Hey,This is Y.R.R,currently working as a software Engineer at Intellect Design Arena Ltd,India. I like to "HOW,WHY,WHAT,WHOM" of everything regardless of what medium i am working in.Follow my Youtube Channel to get latest stuff.

0 comments:

Post a Comment

 

© 2013 YRR Help. All rights resevered. Designed by Templateism

Back To Top