Example 11-1 Creating and Manipulating a DOM Document

This example creates a hierarchical, in-memory representation of an XML document – a DOM document. It uses a handle to this DOM document to manipulate it: print it, change part of it, and print it again after the change. Manipulating the DOM document by its handle also indirectly affects the XML data represented by the document, so that querying that data after the change shows the changed result.

The in-memory document is created from an XMLType variable using PL/SQL function newDOMDocument . The handle to this document is created using function makeNode . The document is written to a VARCHAR2 buffer using function writeToBuffer , and the buffer is printed using DBMS_OUTPUT.put_line .

After manipulating the document using various DBMS_XMLDOM procedures, the (changed) data in the XMLType variable is inserted into a table and queried, showing the change. It is only when the data is inserted into a database table that it becomes persistent; until then, it exists in memory only. This persistence is demonstrated by the fact that the database query is made after the in-memory document (DOMDocument instance) has been freed.

CREATE TABLE person OF XMLType;

DECLARE

var XMLType;

doc DBMS_XMLDOM.DOMDocument;

ndoc DBMS_XMLDOM.DOMNode;

docelem DBMS_XMLDOM.DOMElement;

node DBMS_XMLDOM.DOMNode;

childnode DBMS_XMLDOM.DOMNode;

nodelist DBMS_XMLDOM.DOMNodelist;

buf VARCHAR2(2000);

BEGIN

var := XMLType('ramesh

');

-- Create DOMDocument handle

doc := DBMS_XMLDOM.newDOMDocument(var);

ndoc := DBMS_XMLDOM.makeNode(doc);

DBMS_XMLDOM.writeToBuffer(ndoc, buf);

DBMS_OUTPUT.put_line('Before:

'||buf);

docelem := DBMS_XMLDOM.getDocumentElement(doc);

-- Access element

nodelist := DBMS_XMLDOM.getElementsByTagName(docelem, 'NAME

');

node := DBMS_XMLDOM.item(nodelist, 0);

childnode := DBMS_XMLDOM.getFirstChild(node);

-- Manipulate element

DBMS_XMLDOM.setNodeValue(childnode, 'raj

');

DBMS_XMLDOM.writeToBuffer(ndoc, buf);

DBMS_OUTPUT.put_line('After:

'||buf);

DBMS_XMLDOM.freeDocument(doc);

INSERT INTO person VALUES (var);

END;

/

This produces the following output:

Before:

ramesh

After:

raj

This query confirms that the data has changed:

SELECT * FROM person;

SYS_NC_ROWINFO$

---------------

raj

1 row selected.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐