开发者

How to retrieve a specific XML node from an Oracle table?

开发者 https://www.devze.com 2023-01-18 15:33 出处:网络
I have an oracle table which has a column that stores XML in a CLOB format. The XML has the following syntax:

I have an oracle table which has a column that stores XML in a CLOB format. The XML has the following syntax:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
 <BaseXML Version="2009.4">
 <InvoiceCanvasDetails>
     <Grouping>
       <ParentGroup Name=”Parent group 1” ID=”100”>
        <ParentGroupLineItems>
         <Item ID="461616" Name=”Item 1”>
           <Papers Quantity=10000>
                          <Paper Name="UNCOATED GROUNDWOOD SCA+ (25X38)"    
                                      ID="126287" Weight="1268" Type=”A4” /> 
                          <Paper Name="COATED GROUNDWOOD SCA+ (25X38)"    
                                      ID="126288" Weight="1290" Type=”A4” />
                     </Papers>
              </Item>
       </ParentGroupLineItems>
    </ParentGroup>
  <开发者_如何学编程/Grouping>
 </InvoiceCanvasDetails>
</BaseXML>

Now, I want to retrieve only the Paper information corresponding to each item. ie, Given an item ID, retrieve all the papers associated to it using a query. Please guide me which is the best way to do this.


You can use a combination of extract and extractvalue:

SQL> SELECT extractvalue(column_value, 'Paper/@Name') NAME,
  2         extractvalue(column_value, 'Paper/@ID') ID,
  3         extractvalue(column_value, 'Paper/@Weight') Weight,
  4         extractvalue(column_value, 'Paper/@Type') TYPE
  5    FROM TABLE (SELECT xmlsequence(XMLTYPE(a).extract('BaseXML/' ||
  6                                             'InvoiceCanvasDetails/' ||
  7                                             'Grouping/ParentGroup/' ||
  8                                             'ParentGroupLineItems/' ||
  9                                             'Item/Papers/Paper'))
 10                   FROM t);

NAME                                     ID         WEIGHT     TYPE
---------------------------------------- ---------- ---------- -----
UNCOATED GROUNDWOOD SCA+ (25X38)         126287     1268       A4
COATED GROUNDWOOD SCA+ (25X38)           126288     1290       A4

If you're looking for a specific ID, you can filter data directly in the extract function:

SQL> SELECT extract(XMLTYPE(a),
  2                  'BaseXML/InvoiceCanvasDetails/Grouping/' ||
  3                  'ParentGroup/ParentGroupLineItems/' ||
  4                  'Item/Papers/Paper[@ID="126287"]') ext
  5    FROM t;

EXT
--------------------------------------------------------------------------------
<Paper Name="UNCOATED GROUNDWOOD SCA+ (25X38)" ID="126287" Weight="1268" Type="A
4"/>


Take a look at using XPATH expressions in Oracle.

0

精彩评论

暂无评论...
验证码 换一张
取 消