1. 程式人生 > >PostgreSQL的XML型別

PostgreSQL的XML型別

    xml型別用於儲存XML資料。使用字串也可以儲存XML資料,但不能保證其合法性。支援xml型別後,資料庫會對資料進行合法性檢查,同時提供函式進行型別安全性檢查。

1.xml型別

   xml型別中儲存資料有兩種:documents和content。content可以有多個頂級元素,documents只能有一個頂級元素。預設情況下是content。

    檢視當前的儲存型別:

show xmloption;

    修改當前的儲存型別:

SET xmloption TO document;

    xmlparse函式將字串轉換為XML,函式中的引數指定XML資料的型別。

select xmlparse(document'<title> hello world</title>');

2.xml型別的輸入

    下面兩種等價的語法輸入xml資料。

select xml'<title> hello world</title>';
select '<title> hello world</title>'::xml;

3.xml型別的函式

    PostgreSQL提供了一些函式,可以將資料庫中的內容匯出成XML資料。

3.1 建表

 CREATE TABLE person (
  id  int,
  name varchar(20)
);

3.2 插入資料

insert into person values(1,'April');
insert into person values(2,'Harris');

3.3 執行xml型別的函式

 (1)把表的定義轉成xml的格式,函式定義如下:

   table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text);

select table_to_xmlschema('person'::regclass,true,true,'mydb');

(2)把表的定義和表中的資料

轉成xml的格式,函式定義如下:

    table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text);

select table_to_xml_and_xmlschema('person'::regclass,true,true,'mydb');

(3)把查詢結果中行的定義轉成xml格式,函式定義如下:

    query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text);

select query_to_xmlschema('select * from person',true,true,'mydb');

(4)把查詢結果中行的定義和值轉成xml格式,函式定義如下:

    query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text);

select query_to_xml_and_xmlschema('select * from person',true,true,'mydb');