Parsing XML data stored as CLOB in DB and save attribute values in table

Hello,
I have a CLOB column in table that is holding XML data as follows,
<banners>
<banner-image id="0">
<type>BANNER</type>
<local-path>http.gif</local-path>
<click-through-url>www</click-through-url>
<make>Acura</make>
</banner-image>
<banner-image id="1">
<type>BANNER</type>
<local-path>http.gif</local-path>
<click-through-url>gfrty</click-through-url>
<make>BMW</make>
</banner-image>
</banners>
Now I need to parse thru the above XML data and pull the attribute values to store in another table as follows,
BANNER_IMAGE_ID | TYPE | LOCAL_PATH | CLICK_URL | MAKE
0 | BANNER | http.gif | www | Acura
1 | BANNER | http.gif | gfrty | BMW
And XML data doesn't always end up with 2 rows in this table....some times it may be 3 or 4 as well. It is just that in this example it ended up with 2 rows.
So, I would appreciate if someone can help me find a generic way of doing this,
Thank you in advance,
Madhu.

This is not a reply.. sorry.
I took have a similar problem only..
can you pls help me
XML structure.
<PODetails>
<POHeader>
<CurrencyID>INR</CurrencyID>
<ExchangeRate>1</ExchangeRate>
<RefNo>0080000110</RefNo>
<VendorID>1200</VendorID>
<TransDate>2006-12-20</TransDate>
<DocRelationshipId>PURCHASE</DocRelationshipId>
<LocationID>0000102327</LocationID>
</POHeader>
<POItemDetails>
<ItemID>ARSH1332</ItemID>
<Size>L HS</Size>
<Quality>Q1</Quality>
<CustPO>rush order</CustPO>
<UOM>PC</UOM>
<Quantity>3.000</Quantity>
<PriceValue>2509.5</PriceValue>
<TaxAmount>0.00</TaxAmount>
</POItemDetails>
<POItemDetails>
<ItemID>ARSH1332</ItemID>
<Size>M HS</Size>
<Quality>Q1</Quality>
<CustPO>rush order</CustPO>
<UOM>PC</UOM>
<Quantity>2.000</Quantity>
<PriceValue>1673</PriceValue>
<TaxAmount>0.00</TaxAmount>
</POItemDetails>
<POItemDetails>
<ItemID>ARSH1556</ItemID>
<Size>39FS</Size>
<Quality>Q1</Quality>
<CustPO>rush order</CustPO>
<UOM>PC</UOM>
<Quantity>1.000</Quantity>
<PriceValue>836.5</PriceValue>
<TaxAmount>0.00</TaxAmount>
</POItemDetails>
</PODetails>
The DB is ORACLE 9i
This is stored in a XML table of type XMLTYPE.
THIS I USED THE .extract function to get the values of the nodes.
POHeader details are working fine. But when i get the POItemDetails i am getting 'ARSH1332ARSH1332ARSH1556' when i issue the command
select a.extract('/PODetails/POItemDetails/ItemID/text()').getStringVal() ItemID
FROM xmltable a
WHERE a.existsnode('//POItemDetails/ItemID')=1
Pls Help..
Regds,
Santhoshkumar.G.

Similar Messages

  • How to read XML data stored in CLOB in Concurrent prog Output

    Hi All,
    I'm trying to Generate the XML Data as concurrent Program output. I have a PL/SQL package which generated the XML data by using SQL/XML functions. I'm storing the generated XML data in a CLOB variable. But when i try to read the data using fnd_file.put_line(fnd_file.OUTPUT,XML_Data) it doesn't display data more than 32767 bytes.
    Please help me out to understand what could be done to read the data in chunks. I have tried many logic's to print chunks of data but the output tags are either chopped off and errors out saying Tag not found.
    My logic is as below:
    v_handler:= DBMS_XMLGEN.newContext(v_xml_query);
    --Sets NULL handling options
    DBMS_XMLGen.SetNullHandling(v_handler, dbms_xmlgen.EMPTY_TAG ) ;
    --Set special character handling
    DBMS_XMLGEN.setConvertSpecialChars(v_handler, TRUE);
    -- Specified whether to use an XML attribute to indicate NULLness of particular entity in the XML document
    DBMS_XMLGen.useNullAttributeIndicator(v_handler,TRUE);
    -- set Checking invalid chars
    DBMS_XMLGEN.setCheckInvalidChars(v_handler, TRUE);
    -- get the xml data as required
    v_xml_data:= DBMS_XMLGEN.getXMLtype(v_handler);
    SELECT XMLROOT(v_xml_data.extract('/*'),VERSION '1.0').getClobVal() into v_new_xml_Data from dual;
    -- get the length of the xml generated
    v_clob_len := dbms_lob.getlength(v_new_xml_Data);
    FND_FILE.PUT_LINE(FND_FILE.LOG,'The Clob length is :'|| v_clob_len);
    -- logic to process string more than 32767 Processing by each character
    v_offset :=1;
    while (v_offset <= v_clob_len)
    LOOP
    v_char := dbms_lob.substr(v_new_xml_Data, 1, v_offset);
    IF (v_char = CHR(10))
    then
    fnd_file.new_line(fnd_file.output, 1);
    else
    fnd_file.put(fnd_file.output, v_char);
    end if;
    v_offset := v_offset + 1;
    END LOOP;
    FND_FILE.PUT_LINE(FND_FILE.LOG,'The offset is :'|| v_offset);
    FND_FILE.NEW_LINE(FND_FILE.OUTPUT, 1);
    THe above logic is for character by character which is a performance burden? Please let me know if there is any other work around for this

    Hi,
    Thanks for Replying. I have refered http://blog.oraclecontractors.com/?p=69 and then i added that piece of code. Basically, i'm trying to generate a report using XML publisher. To generate the XML data i'm writing a pl/sql package with SQl/XML functions. DBMS_XMLGEN would help me convert the XML Data as is. When the concurrent program runs this XML data will merge with RTF layout and generate required report. I'm able to generate the Report for data less then 32767 bytes. More than the limit i need to pass chunks of XML data to read as output. That's the reason i'm using fnd_file.output. But it reads only 32767 size at a time.
    WHen i use the given logic, it works perfectly fine, but it loops for each character, for example if you have 30,000 characters it loops the same, which is peformance burden.
    So i tried to write the logic of chunks but still i get the error that XML tag is not found or missing. I'm hoping this is very common issue, but after all my trails, i didn't find the right solution.
    the other logic i tried was :
    v_new_xml_data varchar2(32767)
    v_iterations := CEIL(v_clob_len/v_chunk_length); -- v_chunk_length is 32767 and v_clob_length is length of the XML data stored inthe clob variable
    For i in 0..v_iterations
    LOOP
    FND_FILE.put_line (fnd_file.log,'the loops v_pos :'||i||' and v_clob_length :'||v_clob_len);
    v_new_xml_data := DBMS_LOB.SUBSTR ( V_XML_DATA,v_chunk_length,(i*v_chunk_length)+1);
    FND_FILE.PUT_LINE (FND_FILE.OUTPUT,v_new_xml_data); -- read the output for every 32767 chunks
    FND_FILE.PUT_LINE(FND_FILE.LOG, 'Chunk length is :'||((i*v_chunk_length)+1));
    END LOOP;
    FND_FILE.put_line (fnd_file.log,'out of loop');
    FND_FILE.put_line (fnd_file.log,'length of new xml is '||v_clob_len);
    Please, let me know if you need Further clarifications on the same.

  • Update XML data stored in CLOB Column

    Hi All,
    i am new to Oracle and new to SQL
    i am trying to update XML data stored in CLOB cloumn,data is stored with the follwoing format
    <attrs><attr name="name"><string>Schade</string></attr></attrs>
    i am using the following query for updating the value
    UPDATE PRODUCT p SET ATTRIBUTES_nl_nl=UPDATEXML(XMLTYPE.createXML(ATTRIBUTES_nl_nl),'/attrs/attr[@name="name"]/string/text()','Schade').getClobVal() WHERE p.sku='000000000000040576_200911-5010057'
    this query is working fine but it changing the data to the following format
    <attrs><attr name="name">Schade</attr></attrs>
    some how it is ommiting the <string> tag from it, i am unable to figure it out whats the reason.
    any help in this regard will b e much appriciated
    Thanks in Advance
    -Umesh

    Hi,
    You should have created your own thread for this, and included database version.
    This works for me on 11.2.0.2 and 10.2.0.5 :
    SQL> create table t_org ( xml_clob clob );
    Table created
    SQL>
    SQL> insert into t_org
      2  values(
      3  '<Message>
      4  <Entity>
      5  <ASSIGNMENT>
      6  <OAVendorLocation> </OAVendorLocation>
      7  <Vendorid>1</Vendorid>
      8  </ASSIGNMENT>
      9  </Entity>
    10  </Message>'
    11  );
    1 row inserted
    SQL> commit;
    Commit complete
    SQL> select '*' ||
      2         extractvalue(xmltype(xml_clob),'/Message/Entity/ASSIGNMENT/OAVendorLocation')
      3         || '*' as result
      4  from t_org;
    RESULT
    SQL> update t_org set xml_clob =
      2  updatexml(xmltype(xml_clob),
      3  '/Message/Entity/ASSIGNMENT/OAVendorLocation/text()','LONDON').getClobVal()
      4  ;
    1 row updated
    SQL> select '*' ||
      2         extractvalue(xmltype(xml_clob),'/Message/Entity/ASSIGNMENT/OAVendorLocation')
      3         || '*' as result
      4  from t_org;
    RESULT
    *LONDON*
    Does the OAVendorLocation really have a whitespace value?
    If not then it's expected behaviour, you're trying to update a text() node that doesn't exist. In this case, the solution is to use appendChildXML to create the text() node, or update the whole element.
    Is it your real document? Do you actually have some namespaces?

  • Trying to Insert an XML Element into XML data stored in CLOB column

    Hi all,
    My ORACLE DB version is:
    ('Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production');
    ('PL/SQL Release 11.2.0.2.0 - Production');
    ('CORE 11.2.0.2.0 Production');
    ('TNS for Linux: Version 11.2.0.2.0 - Production');
    ('NLSRTL Version 11.2.0.2.0 - Production');
    I have this XML data stored in a CLOB column:
    <Activity>
         <Changes>     
         </Changes>
         <Inserts>     
         </Inserts>
         <Definition>     
         </Definition>
         <Assignment TYPE="Apply">     
         </Assignment>
         <Spawned>
              <Activity>576D8CD9-57A1-8608-1563-8F6DC74BDF3C</Activity>
              <Activity>11226E79-5D24-02EB-A950-D34A9CCFB3FF</Activity>
              <Activity>DAA68DC0-CA9A-BB15-DE31-9596E19513EE</Activity>
              <Activity>93F667D6-966A-7EAD-9B70-630D9BEFDDD2</Activity>
              <Activity>FA63D9D3-86BB-3FF0-BE69-17EAA7581637</Activity>
         </Spawned>
         <SpawnedBy>AFC49BD4-5AA7-38C0-AE27-F59D16EE1B1C</SpawnedBy>
    </Activity>
    I am in need of some assistance in creating an update that will insert another <Activity>SomeGUID</Activity> into the <Spawned> parent.
    Any help is greatly appreciated.
    Thanks.
    Edited by: 943783 on Dec 14, 2012 12:58 PM

    See XML updating functions : http://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xdb04cre.htm#i1032611
    For example :
    UPDATE my_table t
    SET t.my_clob =
          XMLSerialize(document
            insertChildXML(
              XMLParse(document t.my_clob)
            , '/Activity/Spawned'
            , 'Activity'
            , XMLElement("Activity", 'Some GUID')
    WHERE ...
    ;Although it works, there's overhead introduced by parsing the CLOB, then serializing again.
    Is there any chance you can change the CLOB to SECUREFILE binary XMLType storage instead?
    You would then be able to benefit from optimized piecewise update of the XML and improved storage.

  • How to read XML Data stored as Clob

    Hi
    I am new to clob & XML types...
    An XML data has been inserted into a Clob field in a Oracle(9.2.0.8.0) Table
    CREATE TABLE TEMP
    SNO NUMBER(5),
    STR_VAL LONG,
    CREATED_DT DATE DEFAULT sysdate,
    COL2 CLOB,
    COL3 SYS.XMLTYPE
    SELECT dbms_lob.getlength(col2) from temp
    ->24754
    SQL> select col2 from temp;
    COL2
    &lt;DataSet1&gt;
    &lt;TAGSDATATABLE&gt;
    &lt;TAG_NAME&gt;KST20001&lt;/TAG_NA
    If i use the above stmt it shows only pice of data
    how can i get the actual data from this column.
    could anyone help to get the data.
    Regards
    Prakash
    Edited by: user12957183 on Aug 25, 2010 12:25 AM

    Insert data in to XMLTYPE table from clob variable:
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2  my_clob CLOB := '<DataSet1><TAGSDATATABLE><TAG_NAME>KST20001</TAG_NAME>
      3  </TAGSDATATABLE><TAGSDATATABLE><TAG_NAME>KST20002</TAG_NAME></TAGSDATATABLE>
      4  <TAGSDATATABLE><TAG_NAME>KST20003</TAG_NAME></TAGSDATATABLE>
      5  <TAGSDATATABLE>
      6  <TAG_NAME>KST20004</TAG_NAME>
      7  </TAGSDATATABLE>
      8  <TAGSDATATABLE>
      9  <TAG_NAME>KST20005</TAG_NAME>
    10  </TAGSDATATABLE>
    11  <TAGSDATATABLE>
    12  <TAG_NAME>KST20006</TAG_NAME>
    13  </TAGSDATATABLE>
    14  <TAGSDATATABLE>
    15  <TAG_NAME>KST20007</TAG_NAME>
    16  </TAGSDATATABLE>
    17  <TAGSDATATABLE>
    18  <TAG_NAME>KST20008</TAG_NAME>
    19  </TAGSDATATABLE>
    20  <TAGSDATATABLE>
    21  <TAG_NAME>KST20009</TAG_NAME>
    22  </TAGSDATATABLE>
    23  <TAGSDATATABLE>
    24  <TAG_NAME>KST20010</TAG_NAME>
    25  </TAGSDATATABLE>
    26  <TAGSDATATABLE>
    27  <TAG_NAME>KST20009</TAG_NAME>
    28  </TAGSDATATABLE>
    29  </DataSet1>';
    31  BEGIN
    33  INSERT INTO my_tab1 VALUES(XMLTYPE(my_clob));
    34* end;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> desc my_tab1;
    Name                                                                                                                  
    TABLE of XMLTYPE
    SQL>
    -- For larger data:
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2  my_clob CLOB := '<DataSet1>
      3  <TAGSDATATABLE>
      4  <TAG_NAME>KST20001</TAG_NAME>
      5  </TAGSDATATABLE>
      6  <TAGSDATATABLE>
      7  <TAG_NAME>KST20002</TAG_NAME>
      8  </TAGSDATATABLE>
      9  <TAGSDATATABLE>
    10  <TAG_NAME>KST20003</TAG_NAME>
    11  </TAGSDATATABLE>
    12  <TAGSDATATABLE>
    13  <TAG_NAME>KST20004</TAG_NAME>
    14  </TAGSDATATABLE>
    15  <TAGSDATATABLE>
    16  <TAG_NAME>KST20005</TAG_NAME>
    17  </TAGSDATATABLE>
    18  <TAGSDATATABLE>
    19  <TAG_NAME>KST20006</TAG_NAME>
    20  </TAGSDATATABLE>
    21  <TAGSDATATABLE>
    22  <TAG_NAME>KST20007</TAG_NAME>
    23  </TAGSDATATABLE>
    24  <TAGSDATATABLE>
    25  <TAG_NAME>KST20008</TAG_NAME>
    26  </TAGSDATATABLE>
    27  <TAGSDATATABLE>
    28  <TAG_NAME>KST20009</TAG_NAME>
    29  </TAGSDATATABLE>
    30  <TAGSDATATABLE>
    31  <TAG_NAME>KST20010</TAG_NAME>
    32  </TAGSDATATABLE>
    33  <TAGSDATATABLE>
    34  <TAG_NAME>KST20009</TAG_NAME>
    35  </TAGSDATATABLE>
    36  <TAGSDATATABLE>
    37  <TAG_NAME>KST20009</TAG_NAME>
    38  </TAGSDATATABLE>
    39  <TAGSDATATABLE>
    40  <TAG_NAME>KST20009</TAG_NAME>
    41  </TAGSDATATABLE>
    42  <TAGSDATATABLE>
    43  <TAG_NAME>KST20009</TAG_NAME>
    44  </TAGSDATATABLE>
    45  <TAGSDATATABLE>
    46  <TAG_NAME>KST20010</TAG_NAME>
    47  </TAGSDATATABLE>
    48  <TAGSDATATABLE>
    49  <TAG_NAME>KST20009</TAG_NAME>
    50  </TAGSDATATABLE>
    51  <TAGSDATATABLE>
    52  <TAG_NAME>KST20009</TAG_NAME>
    53  </TAGSDATATABLE>
    54  <TAGSDATATABLE>
    55  <TAG_NAME>KST20009</TAG_NAME>
    56  </TAGSDATATABLE>
    57  <TAGSDATATABLE>
    58  <TAG_NAME>KST20009</TAG_NAME>
    59  </TAGSDATATABLE>
    60  <TAGSDATATABLE>
    61  <TAG_NAME>KST20010</TAG_NAME>
    62  </TAGSDATATABLE>
    63  <TAGSDATATABLE>
    64  <TAG_NAME>KST20009</TAG_NAME>
    65  </TAGSDATATABLE>
    66  <TAGSDATATABLE>
    67  <TAG_NAME>KST20009</TAG_NAME>
    68  </TAGSDATATABLE>
    69  <TAGSDATATABLE>
    70  <TAG_NAME>KST20009</TAG_NAME>
    71  </TAGSDATATABLE>
    72  <TAGSDATATABLE>
    73  <TAG_NAME>KST20009</TAG_NAME>
    74  </TAGSDATATABLE>
    75  <TAGSDATATABLE>
    76  <TAG_NAME>KST20010</TAG_NAME>
    77  </TAGSDATATABLE>
    78  <TAGSDATATABLE>
    79  <TAG_NAME>KST20009</TAG_NAME>
    80  </TAGSDATATABLE>
    81  <TAGSDATATABLE>
    82  <TAG_NAME>KST20009</TAG_NAME>
    83  </TAGSDATATABLE>
    84  <TAGSDATATABLE>
    85  <TAG_NAME>KST20009</TAG_NAME>
    86  </TAGSDATATABLE>
    87  <TAGSDATATABLE>
    88  <TAG_NAME>KST20009</TAG_NAME>
    89  </TAGSDATATABLE>
    90  <TAGSDATATABLE>
    91  <TAG_NAME>KST20010</TAG_NAME>
    92  </TAGSDATATABLE>
    93  <TAGSDATATABLE>
    94  <TAG_NAME>KST20009</TAG_NAME>
    95  </TAGSDATATABLE>
    96  <TAGSDATATABLE>
    97  <TAG_NAME>KST20009</TAG_NAME>
    98  </TAGSDATATABLE>
    99  <TAGSDATATABLE>
    100  <TAG_NAME>KST20009</TAG_NAME>
    101  </TAGSDATATABLE>
    102  <TAGSDATATABLE>
    103  <TAG_NAME>KST20009</TAG_NAME>
    104  </TAGSDATATABLE>
    105  <TAGSDATATABLE>
    106  <TAG_NAME>KST20010</TAG_NAME>
    107  </TAGSDATATABLE>
    108  <TAGSDATATABLE>
    109  <TAG_NAME>KST20009</TAG_NAME>
    110  </TAGSDATATABLE>
    111  <TAGSDATATABLE>
    112  <TAG_NAME>KST20009</TAG_NAME>
    113  </TAGSDATATABLE>
    114  <TAGSDATATABLE>
    115  <TAG_NAME>KST20009</TAG_NAME>
    116  </TAGSDATATABLE>
    117  <TAGSDATATABLE>
    118  <TAG_NAME>KST20009</TAG_NAME>
    119  </TAGSDATATABLE>
    120  <TAGSDATATABLE>
    121  <TAG_NAME>KST20010</TAG_NAME>
    122  </TAGSDATATABLE>
    123  <TAGSDATATABLE>
    124  <TAG_NAME>KST20009</TAG_NAME>
    125  </TAGSDATATABLE>
    126  <TAGSDATATABLE>
    127  <TAG_NAME>KST20009</TAG_NAME>
    128  </TAGSDATATABLE>
    129  <TAGSDATATABLE>
    130  <TAG_NAME>KST20009</TAG_NAME>
    131  </TAGSDATATABLE>
    132  <TAGSDATATABLE>
    133  <TAG_NAME>KST20009</TAG_NAME>
    134  </TAGSDATATABLE>
    135  <TAGSDATATABLE>
    136  <TAG_NAME>KST20010</TAG_NAME>
    137  </TAGSDATATABLE>
    138  <TAGSDATATABLE>
    139  <TAG_NAME>KST20009</TAG_NAME>
    140  </TAGSDATATABLE>
    141  <TAGSDATATABLE>
    142  <TAG_NAME>KST20009</TAG_NAME>
    143  </TAGSDATATABLE>
    144  <TAGSDATATABLE>
    145  <TAG_NAME>KST20009</TAG_NAME>
    146  </TAGSDATATABLE>
    147  </DataSet1>';
    148  l_xmltype xmltype;
    149  BEGIN
    150  --l_xmltype := my_clob;
    151  INSERT INTO my_tab1 VALUES(XMLTYPE(my_clob));
    152* end;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> Edited by: AP on Aug 25, 2010 4:46 AM

  • Can I create an XSD from XML data in a CLOB?

    Environment:
    Oracle 11.2.0.3 EE on Solaris.
    Very much an XML newbie so please be kind! 
    I have spent the past few days pouring through the documentation and various blogs, especially this one, but ... I need some help.
    I am trying to extract XML data stored in a CLOB and produce a flat file for the user's consumption.
    They have sent me what they think is the XSD for the XML data but when I look at the data in the CLOB I don't see the tags documented in the XSD.
    I'd like to produce an XSD based on the actual data to compare with what they've sent.
    Is this possible?
    I am able to query the XML data using the tags I see in the data using XMLTable and it's working fine.
    Any help is greatly appreciated.
    -gary

    Welcome to the XML side of the world, where you will love it and curse it, just like any other piece of technology.
    So as I understand it, the scope of your operation is to extract information from an XML file and then write that information to disk, correct?
    Some questions
    - Why is the XML stored in a CLOB instead of an XMLType column?  Without knowing the system history, it is a valid question.
    - How big are the XML?  The reason I ask this is because when the XML is stored in XMLType columns (of Object Relational structure or SECUREFILE BINARY XML format), then Oracle can parse the XML substantially easier than when it is stored as a CLOB.  If the XML is fairly small, you may see no performance difference between the two.
    The Oracle DB itself has no built in ability to generate a schema from an XML file.  In order to do that, you would need to use some third party tool that has that functionality built in.  For example, XML Spy can do this.  Other tools can as well, but that is what came to mind first as it is what I use.  The one thing to remember is that the schema it builds represents that one instance of XML.  Other instances of XML may be different and not validate against the schema you generated, but still have been valid against the unknown original schema.
    You can register the schema in the database and then use the XML to create an XMLType instance associated to the schema and then validate the XML that way.  One example can be found at XML DB FAQ and here is another example Re: XML Schema validation
    Hope that helps you continue on.

  • Script for parsing xml data and inserting in DB

    Thank you for reading.
    I have the following example XML in an XML file. I need to write a script that can insert this data into an Oracle table. The table does not have primary keys. The data just needs to be inserted.
    I do not have xsd file in this scenario. Please suggest how to modify Method 1 https://community.oracle.com/thread/1115266?tstart=0 mentioned so that I can call the XML mentioned below and insert into a table
    Method 1
    Create or replace procedure parse_xml is 
      l_bfile   BFILE; 
      l_clob    CLOB; 
      l_parser  dbms_xmlparser.Parser; 
      l_doc     dbms_xmldom.DOMDocument; 
      l_nl      dbms_xmldom.DOMNodeList; 
      l_n       dbms_xmldom.DOMNode; 
      l_file      dbms_xmldom.DOMNodeList; 
      l_filen       dbms_xmldom.DOMNode; 
      lv_value VARCHAR2(1000); 
       l_ch      dbms_xmldom.DOMNode; 
    l_partname varchar2(100); 
    l_filename varchar2(1000); 
      l_temp    VARCHAR2(1000); 
      TYPE tab_type IS TABLE OF tab_software_parts%ROWTYPE; 
      t_tab  tab_type := tab_type(); 
    BEGIN 
      l_bfile := BFileName('DIR1', 'SoftwareParts.xml'); 
      dbms_lob.createtemporary(l_clob, cache=>FALSE); 
      dbms_lob.open(l_bfile, dbms_lob.lob_readonly); 
      dbms_lob.loadFromFile(dest_lob => l_clob,    src_lob  => l_bfile,    amount   => dbms_lob.getLength(l_bfile)); 
      dbms_lob.close(l_bfile);  
      dbms_session.set_nls('NLS_DATE_FORMAT','''DD-MON-YYYY'''); 
      l_parser := dbms_xmlparser.newParser; 
      dbms_xmlparser.parseClob(l_parser, l_clob); 
      l_doc := dbms_xmlparser.getDocument(l_parser); 
        dbms_lob.freetemporary(l_clob); 
      dbms_xmlparser.freeParser(l_parser); 
      l_nl := dbms_xslprocessor.selectNodes(dbms_xmldom.makeNode(l_doc),'/PartDetails/Part'); 
        FOR cur_emp IN 0 .. dbms_xmldom.getLength(l_nl) - 1 LOOP 
        l_n := dbms_xmldom.item(l_nl, cur_emp); 
        t_tab.extend; 
        dbms_xslprocessor.valueOf(l_n,'Name/text()',l_partname); 
        t_tab(t_tab.last).partname := l_partname; 
        l_file := dbms_xslprocessor.selectNodes(l_n,'Files/FileName'); 
        FOR cur_ch IN 0 .. dbms_xmldom.getLength(l_file) - 1 LOOP 
          l_ch := dbms_xmldom.item(l_file, cur_ch); 
          lv_value := dbms_xmldom.getnodevalue(dbms_xmldom.getfirstchild(l_ch)); 
          if t_tab(t_tab.last).partname is null then t_tab(t_tab.last).partname := l_partname; end if; 
          t_tab(t_tab.last).filename := lv_value; 
        t_tab.extend; 
       END LOOP; 
       END LOOP; 
        t_tab.delete(t_tab.last); 
      FOR cur_emp IN t_tab.first .. t_tab.last LOOP 
      if t_tab(cur_emp).partname is not null and  t_tab(cur_emp).filename is not null then 
        INSERT INTO tab_software_parts 
        VALUES 
        (t_tab(cur_emp).partname, t_tab(cur_emp).filename); 
        end if; 
      END LOOP; 
      COMMIT; 
      dbms_xmldom.freeDocument(l_doc); 
    EXCEPTION 
      WHEN OTHERS THEN 
        dbms_lob.freetemporary(l_clob); 
        dbms_xmlparser.freeParser(l_parser); 
        dbms_xmldom.freeDocument(l_doc); 
    END; 
    <TWObject className="TWObject">
      <array size="240">
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[30]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[GB]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_GB001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
        <item>
          <variable type="QuestionDetail">
            <questionId type="String"><![CDATA[40]]></questionId>
            <questionType type="questionType"><![CDATA[COUNTRY]]></questionType>
            <country type="String"><![CDATA[DE]]></country>
            <questionText type="String"><![CDATA[Please indicate]]></questionText>
            <optionType type="String"><![CDATA[RadioButton]]></optionType>
            <answerOptions type="String[]">
              <item><![CDATA[Yes]]></item>
              <item><![CDATA[No]]></item>
            </answerOptions>
            <ruleId type="String"><![CDATA[CRP_Q0001]]></ruleId>
            <parentQuestionId type="String"></parentQuestionId>
            <parentQuestionResp type="String"></parentQuestionResp>
          </variable>
        </item>
      </array>
    </TWObject>

    Reposted as
    Script to parse XML data into Oracle DB

  • How to parsing xml data in sql statement??

    Hi friends, I have a table which contain column as clob ,stores in xml format, for example my column contain xml data like this
    <Employees xmlns="http://TargetNamespace.com/read_emp">
       <C1>106</C1>
       <C2>Harish</C2>
       <C3>1998-05-12</C3>
       <C4>HR</C4>
       <C5>1600</C5>
       <C6>10</C6>
    </Employees>
      Then how to extract the data in above xml column data using SQL statement...

    Duplicate post
    How to parsing xml data in sql statement??

  • How to insert more than 32k xml data into oracle clob column

    how to insert more than 32k xml data into oracle clob column.
    xml data is coming from java front end
    if we cannot use clob than what are the different options available

    Are you facing any issue with my code?
    String lateral size error will come when you try to insert the full xml in string format.
    public static boolean writeCLOBData(String tableName, String id, String columnName, String strContents) throws DataAccessException{
      boolean isUpdated = true;
      Connection connection = null;
      try {
      connection = ConnectionManager.getConnection ();
      //connection.setAutoCommit ( false );
      PreparedStatement PREPARE_STATEMENT = null;
      String sqlQuery = "UPDATE " + tableName + " SET " + columnName + "  = ?  WHERE ID =" + id;
      PREPARE_STATEMENT = connection.prepareStatement ( sqlQuery );
      // converting string to reader stream
      Reader reader = new StringReader ( strContents );
      PREPARE_STATEMENT.setClob ( 1, reader );
      // return false after updating the clob data to DB
      isUpdated = PREPARE_STATEMENT.execute ();
      PREPARE_STATEMENT.close ();
      } catch ( SQLException e ) {
      e.printStackTrace ();
      finally{
      return isUpdated;
    Try this JAVA code.

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • How to parse xml data into java component

    hi
    everybody.
    i am new with XML, and i am trying to parse xml data into a java application.
    can anybody guide me how to do it.
    the following is my file.
    //MyLogin.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class MyLogin extends JFrame implements ActionListener
         JFrame loginframe;
         JLabel labelname;
         JLabel labelpassword;
         JTextField textname;
         JPasswordField textpassword;
         JButton okbutton;
         String name = "";
         FileOutputStream out;
         PrintStream p;
         Date date;
         GregorianCalendar gcal;
         GridBagLayout gl;
         GridBagConstraints gbc;
         public MyLogin()
              loginframe = new JFrame("Login");
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              labelname = new JLabel("User");
              labelpassword = new JLabel("Password");
              textname = new JTextField("",9);
              textpassword = new JPasswordField(5);
              okbutton = new JButton("OK");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 5;
              gl.setConstraints(labelname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 5;
              gl.setConstraints(textname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 10;
              gl.setConstraints(labelpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 10;
              gl.setConstraints(textpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 15;
              gl.setConstraints(okbutton,gbc);
              Container contentpane = getContentPane();
              loginframe.setContentPane(contentpane);
              contentpane.setLayout(gl);
              contentpane.add(labelname);
              contentpane.add(labelpassword);
              contentpane.add(textname);
              contentpane.add(textpassword);
              contentpane.add(okbutton);
              okbutton.addActionListener(this);
              loginframe.setSize(300,300);
              loginframe.setVisible(true);
         public static void main(String a[])
              new MyLogin();
         public void reset()
              textname.setText("");
              textpassword.setText("");
         public void run()
              try
                   String text = textname.getText();
                   String blank="";
                   if(text.equals(blank))
                      System.out.println("First Enter a UserName");
                   else
                        if(text != blank)
                             date = new Date();
                             gcal = new GregorianCalendar();
                             gcal.setTime(date);
                             out = new FileOutputStream("log.txt",true);
                             p = new PrintStream( out );
                             name = textname.getText();
                             String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
                             p.println(entry);
                             System.out.println("Record Saved");
                             reset();
                             p.close();
              catch (IOException e)
                   System.err.println("Error writing to file");
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equals("OK"))
                   run();
                   //loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    hi, thanks for ur reply.
    i visited that url, i was able to know much about xml.
    so now my requirement is DOM.
    but i dont know how to code in my existing file.
    means i want to know what to link all my textfield to xml file.
    can u please help me out. i am confused.
    waiting for ur reply

  • How to query XML data stored in a CLOB column

    I don't know XMLDB, so I have a dumb question about querying XML data which is saved as CLOB in a table.
    I have a table (OLAP_AW_PRC), with a CLOB column - AW_XML_TMPL_VAL
    This column contains this xml data - [click here|http://www.nasar.net/aw.xml]
    Now I want to query the data using the xml tags - like returning the name of AW. This is where I am having trouble, how to query the data from AW_XML_TMPL_VAL clob column.
    The following query generates error:
    ORA-31011: XML parsing failed.
    ORA-19202: Error occurred in XML processing
    LPX-00229: input source is empty
    SELECT
    extractValue(value(x), '/AW/LongName') as "AWNAME"
    from
    OLAP_AW_PRC,
    table(xmlsequence(extract (xmltype(AW_XML_TMPL_VAL), '/AWXML/AWXML.content/Create/ActiveObject/AW'))) x
    where
    extractValue(value(x) , '/AW/Name') = 'OMCR4'
    - Nasar

    Mark,
    Thanks. This is exactly what I was looking for.
    After doing @Name in both places (SELECT and WHERE clause) it worked.
    Now I have one more question.
    There are multiple DIMENSION tags in my xml, and I want to see the NAME attribute values for all of those DIMENSIONs. The following query returns
    ORA-19025: EXTRACTVALUE returns value of only one node.
    Cause: Given XPath points to more than one node.
    Action: Rewrite the query so that exactly one node is returned.
    SELECT
    extractValue(value(x), '/AW/@Name') as "AW",
    extractValue(value(x), '/AW/Dimension/@Name') as "DIMENSIONS"
    from
    OLAP_AW_PRC,
    table(xmlsequence(extract (xmltype(AW_XML_TMPL_VAL), '/AWXML/AWXML.content/Create/ActiveObject/AW'))) x
    where
    extractValue(value(x) , '/AW/@Name') = 'OMCR4'

  • XML data 32K into CLOB

    Hi all,
    I am trying to use UTL_FILE.PUT_LINE to output an XML file. This xml file is the result of a select query. Hence converting the result of the select query into xml format using dbms_xmlgen.getxml and storing it in a variable. But the resultant xml data > 32k . What would be the best way to store it in variable? When using CLOB datatype, getting a numeric value error.
    Thanks in advance.

    As you didn't post the code, nor included a four digit database version, you are asking someone to look in a crystal ball.
    Sorry, they are out for repair.
    Also the XDB forum would be more appropriate.
    Sybrand Bakker
    Senior Oracle DBA

  • Form or form on report to update XML tagS stored in CLOB field.

    I would like to create a form or a form on a report
    where i can update xml tags. The xml data is stored in a CLOB field.
    sample CLOB DATA
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
    <preferences EXTERNAL_XML_VERSION="1.0">
    <root type="user">
    <map />
    <node name="com">
    <map />
    <node name="mynode">
    <map />
    <node name="utils">
    <map />
    <node name="properties">
    <map>
    <entry key="Save" value="ON" />
    <entry key="TM_PORT" value="55555" />
    <entry key="TM_PORT2" value="7777" />
    <entry key="SubID" value="all" />
    <entry key="UserDBUsr" value="myuser" />
    <entry key="JMS_JDBC" value="OFF" />
    <entry key="Side" value="BUY" />
    <entry key="HEALTH_MONITOR_CRITICAL_DISK_SPACE" value="500" />
    <entry key="HEALTH_MONITOR_WARNING_DISK_SPACE" value="750" />
    <entry key="HEALTH_MONITOR_PERIOD" value="600000" />
    </map>
    </node>
    </node>
    </node>
    </node>
    </root>
    </preferences>
    the goal is to have a form where i can view and update the "value" of following:
    TM_PORT
    TM_PORT2
    SubID
    UserDBUsr
    JMS_JDBC
    Side
    HEALTH_MONITOR_CRITICAL_DISK_SPACE
    HEALTH_MONITOR_WARNING_DISK_SPACE
    HEALTH_MONITOR_PERIOD
    I have searched around this forum but could not find an example.
    it would be cool if I could also load the an xml file into the clob.
    Thank you.

    Hi,
    I think you just study first the topics about XML DB to understand how to manupulate xml data in the database.
    See:
    http://www.oracle.com/technology/tech/xml/xmldb/index.html
    and
    XML DB
    Regards,
    Cafer

  • How to Parse XML Store in a CLOB in a SQL

    I'm rather new in using XML concepts in a SQL. Here is my dilemma:
    I have a table with following definition:
    CREATE TABLE extension
    extension_id NUMBER(10) NOT NULL,
    extension_content CLOB NOT NULL,
    fk_transaction_id NUMBER(10),
    fk_batch_id NUMBER(10)
    Where XML format type data is stored and here is sample of data there:
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    300, '<Extension>
    <controlNumber>5070</controlNumber>
    <depositDate1>031105</depositDate1>
    <depositDate2>031105</depositDate2>
    <recordType>7</recordType>
    <sequenceNo>1</sequenceNo>
    <statementNo>B5653047</statementNo>
    </Extension>'
    , 207, NULL);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    301, '<Extension>
    <controlNumber>5070</controlNumber>
    <depositDate1>031105</depositDate1>
    <depositDate2>031105</depositDate2>
    <recordType>7</recordType>
    <sequenceNo>2</sequenceNo>
    <statementNo>B5653047</statementNo>
    </Extension>'
    , 208, NULL);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    586, '<Extension>
    <controlNumber>5157</controlNumber>
    <headerId>ID UEA13700 CLASS C NAME</headerId>
    <recordType>7</recordType>
    </Extension>'
    , NULL, 538);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    290, '<Extension>
    <depositDate>40521</depositDate>
    <destination exception="empty"></destination>
    <x1Number>845734</x1Number>
    <origin>21000021</origin>
    <overflowCount>0</overflowCount>
    </Extension>'
    , NULL, 217);
    Could you kindly help me to write a SQL which will retrieve the first rows where there are <controlNumber>, <depositDate1> and <depositDate2> in the column as?:
    SELECT extension_id, ?extension_content? controlnumber, ??extension_content?? depositdate1, ???extension_content??? depositdate3 FROM Extension
    WHERE...
    The only way I could do was using several SUBSTR and INSTR on TO_CHAR(extension_content) which I don't think was a good way.
    Thank you very much in advance for your help and your sample example.
    Adam Tadj.

    if you want to do it with SQL you should change the data type of the EXTENSION_CONTENT from CLOB to XMLTYPE so that you can treat the content in the column as XML and use functions (EXTRACT, EXTRACTVALUE etc...) available in the database to retrieve what you want.
    but for this your database version should be atleast 9.2.0.4 and above.
    here is the modified example.
    CREATE TABLE extension
    extension_id NUMBER(10) NOT NULL,
    extension_content XMLTYPE NOT NULL,
    fk_transaction_id NUMBER(10),
    fk_batch_id NUMBER(10)
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    300, xmltype('<Extension>
    <controlNumber>5070</controlNumber>
    <depositDate1>031105</depositDate1>
    <depositDate2>031105</depositDate2>
    <recordType>7</recordType>
    <sequenceNo>1</sequenceNo>
    <statementNo>B5653047</statementNo>
    </Extension>')
    , 207, NULL);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    301, xmltype('<Extension>
    <controlNumber>5070</controlNumber>
    <depositDate1>031105</depositDate1>
    <depositDate2>031105</depositDate2>
    <recordType>7</recordType>
    <sequenceNo>2</sequenceNo>
    <statementNo>B5653047</statementNo>
    </Extension>')
    , 208, NULL);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    586, xmltype('<Extension>
    <controlNumber>5157</controlNumber>
    <headerId>ID UEA13700 CLASS C NAME</headerId>
    <recordType>7</recordType>
    </Extension>')
    , NULL, 538);
    INSERT INTO EXTENSION ( EXTENSION_ID, EXTENSION_CONTENT, FK_TRANSACTION_ID,
    FK_BATCH_ID ) VALUES (
    290, xmltype('<Extension>
    <depositDate>40521</depositDate>
    <destination exception="empty"></destination>
    <x1Number>845734</x1Number>
    <origin>21000021</origin>
    <overflowCount>0</overflowCount>
    </Extension>')
    , NULL, 217);
    set linesize 1000
    column extension_id format 999999
    column controlnumber format 999999
    select EXTENSION_ID
    ,extractvalue(EXTENSION_CONTENT, '/Extension/controlNumber') ControlNumber
    ,extractvalue(EXTENSION_CONTENT, '/Extension/depositDate') DepositDate
    from extension
    /

Maybe you are looking for