Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle plsql: how to parse XML and insert into table

Tags:

How to load a nested xml file into database table ?

<?xml version="1.0" ?>  <person>    <row>        <name>Tom</name>        <Address>            <State>California</State>            <City>Los angeles</City>        </Address>    </row>    <row>        <name>Jim</name>        <Address>            <State>California</State>            <City>Los angeles</City>        </Address>    </row> </person>        

In this xml, person is the table name , name is the filed name, Tom is its filed value. Address is a subtable and state and city is two column inside Address. I want to insert the person row into person table, if it failed , do not insert into address table. This xml could be very big. What's the best solution to do this ?

like image 287
Frank Avatar asked Oct 19 '12 21:10

Frank


People also ask

How do I import XML into Oracle SQL Developer?

Import an XML File into Oracle Table Using Oracle SQL Developer. First, convert your XML file to CSV, by clicking on the following link Convert XML to CSV. Paste your XML file contents into the text box of the website, and then you would be able to download the CSV file.

How do you display data in a table format in XML?

If your data or table contains an XML column or LOB data, you must use the DATAFORMAT=XML clause on the EXPORT DATA or EXPORT TABLE command. This format can also be used when the data or table to be exported does not contain an XML column or LOB data.

How can you insert data using PL SQL?

In PL/SQL, we can insert the data into any table using the SQL command INSERT INTO. This command will take the table name, table column and column values as the input and insert the value in the base table.


1 Answers

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE   x XMLType := XMLType(     '<?xml version="1.0" ?>  <person>    <row>        <name>Tom</name>        <Address>            <State>California</State>            <City>Los angeles</City>        </Address>    </row>    <row>        <name>Jim</name>        <Address>            <State>California</State>            <City>Los angeles</City>        </Address>    </row> </person>'); BEGIN   FOR r IN (     SELECT ExtractValue(Value(p),'/row/name/text()') as name           ,ExtractValue(Value(p),'/row/Address/State/text()') as state           ,ExtractValue(Value(p),'/row/Address/City/text()') as city     FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p     ) LOOP     -- do whatever you want with r.name, r.state, r.city   END LOOP; END; 
like image 193
Jeffrey Kemp Avatar answered Sep 22 '22 17:09

Jeffrey Kemp