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');