Search code examples
sqloracle-databaseclobxmltype

Get xmltype in field in Oracle column CLOB


I have a column CLOB type that contain xml format.

I need to get with a simple query all different type from this field:

Ex. The field contain different types:

First record:
<Message type="New Address" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

Second record:
<Message type="Added Email" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

Third record:
<Message type="New Order" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

I would like to retrieve:

New Address
Added Email
New Order

Solution

  • This works for your data:

    select xmlquery('/*/@type'
      passing xmltype(<clob column>)
      returning content)
    from <your table>;
    

    Demo:

    create table t42 (clob_col clob);
    insert into t42 values ('<Message type="New Address" xmlns="..."><Customer type="x"></Customer></Message>');
    insert into t42 values ('<Message type="Added Email" xmlns="..."><Customer></Customer></Message>');
    insert into t42 values ('<Message type="New Order" xmlns="..."><Customer></Customer></Message>');
    
    select xmlquery('/*/@type'
      passing xmltype(t42.clob_col)
      returning content)
    from t42;
    
    XMLQUERY('/*/@TYPE'PASSINGXMLTYPE(T42.CLOB_COL)RETURNINGCONTENT)
    ----------------------------------------------------------------
    New Address
    Added Email
    New Order
    

    Or this:

    select xmltype(<clob_column>).extract('/*/@type')
    from <your table>;
    

    Demo:

    select xmltype(clob_col).extract('/*/@type')
    from t42;
    
    XMLTYPE(CLOB_COL).EXTRACT('/*/@TYPE')
    -------------------------------------
    New Address
    Added Email
    New Order
    

    Read more about querying XML.