Convert XML Document to Oracle Types
Mulai versi 9 oracle mengenalkan tipe data XMLTYPE. Untuk penjelasan tentang XMLTYPE bisa dilihat di postingan sebelumnya, sekarang kita mencoba memanfaatkan XMLTYPE. Tujuan tulisan ini adalah mengubah XML document ke Oracle Type. Misal saya mempunyai dokumen XML seperti dibawah ini :
<?xml version="1.0"?> <SalesDoc> <salesDate>22/01/2011</salesDate> <terminalName>BDG01</terminalName> <Product> <ProductId>P001</ProductId> <ProductName>Product 1</ProductName> <ProductQty>10</ProductQty> <ProductPrice>200000<ProductPrice> </Product> </SalesDoc>
Kita ingin merubah dokumen XML diatas menjadi Oracle Types.Pertama yang harus kita lakukan adalah membuat Oracle Type dan langkah berikutnya adalah kita parsing XML dan kita assignment ke Tipe yang sudah kita buat.
DECLARE
TYPE T_SALES_DOC IS RECORD (
salesDate DATE,
brachName VARCHAR2 (20),
productId VARCHAR2 (10),
productName VARCHAR2 (40),
productQty INTEGER,
productPrice NUMBER (10)
);
TYPE T_SALES_LIST IS TABLE OF T_SALES_DOC;
v_xmltype XMLTYPE; -- variable untuk menyimpan document xml;
v_salesDoc T_SALES_LIST := T_SALES_LIST ();
v_dom DBMS_XMLDOM.DOMDocument;
v_domNodeList DBMS_XMLDOM.DOMNodeList;
v_length INTEGER;
v_node DBMS_XMLDOM.DOMNode;
v_xmlstr VARCHAR2 (400);
BEGIN
v_xmlstr :=
'<?xml version="1.0"?>
<SalesDoc>
<salesDate>22/01/2011</salesDate>
<terminalName>BDG01</terminalName>
<Product>
<ProductId>P001</ProductId>
<ProductName>Product 1</ProductName>
<ProductQty>10</ProductQty>
<ProductPrice>200000</ProductPrice>
</Product>
</SalesDoc>';
v_xmltype := XMLTYPE (v_xmlstr);
v_dom := DBMS_XMLDOM.NEWDOMDOCUMENT (xmldoc => v_xmltype);
v_domNodeList :=
DBMS_XSLPROCESSOR.selectNodes (DBMS_XMLDOM.makeNode (v_dom),
'/SalesDoc/Product'
);
v_length := DBMS_XMLDOM.getLength (v_domNodeList);
FOR i IN 0 .. (v_length - 1)
LOOP
v_node := DBMS_XMLDOM.item (v_domNodeList, i);
v_salesDoc.EXTEND;
DBMS_XSLPROCESSOR.valueOf (v_node,
'ProductId/text()',
v_salesDoc (v_salesDoc.LAST).ProductId
);
DBMS_XSLPROCESSOR.valueOf (v_node,
'ProductName/text()',
v_salesDoc (v_salesDoc.LAST).ProductName
);
DBMS_XSLPROCESSOR.valueOf (v_node,
'ProductQty/text()',
v_salesDoc (v_salesDoc.LAST).ProductQty
);
DBMS_XSLPROCESSOR.valueOf (v_node,
'ProductPrice/text()',
v_salesDoc (v_salesDoc.LAST).ProductPrice
);
END LOOP;
-- menambilkan hasil ke layar
FOR i IN v_salesDoc.FIRST .. v_salesDoc.LAST
LOOP
DBMS_OUTPUT.put_line ('product ID : ' || v_salesDoc (i).ProductId);
DBMS_OUTPUT.put_line ('ProductName : ' || v_salesDoc (i).ProductName);
DBMS_OUTPUT.put_line ('ProductQty : ' || v_salesDoc (i).ProductQty);
DBMS_OUTPUT.put_line ('ProductPrice : ' || v_salesDoc (i).ProductPrice);
END LOOP;
END;
berikut hasil contoh running dari program diatas
