table_to_xml() 是一个系统函数,用于将表的内容映射到 XML。
table_to_xml() 添加于 PostgreSQL 8.3。
用法
table_to_xml (tableregclass,nullsboolean,tableforestboolean,targetnstext)
→xml
当 tableforest 设置为 true 时,每个列集都包含在一个 <tablename> 元素内;当设置为 false 时,每个列集都包含在一个 <row> 元素内,该元素又包含在一个外层的 <tablename> 元素内。
nulls,当设置为 true 时,将在输出中以以下方式表示 NULL 值:
<columnname xsi:nil="true"/>
如果 nulls 设置为 false,则 NULL 值将从输出中省略。
targetns 指定结果的 XML 命名空间。如果提供空字符串,则不使用命名空间。请注意,如果提供 NULL,则函数将返回 NULL。
函数 table_to_xmlschema() 提供描述 table_to_xml() 执行的映射的XML Schema文档。table_to_xml_and_xmlschema() 结合了这两个函数。
变更历史
- PostgreSQL 8.3
- 已添加 (commit 355e05ab)
示例
table_to_xml() 的基本用法示例
postgres=# CREATE TABLE foo (id INT, val TEXT);
CREATE TABLE
postgres=# INSERT INTO foo VALUES(generate_series(1,2), clock_timestamp());
INSERT 0 2
postgres=# SELECT table_to_xml('foo'::regclass, true, true, '');
table_to_xml
-------------------------------------------------------------
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
<val>2023-09-18 19:33:41.91568+09</val> +
</foo> +
+
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
<val>2023-09-18 19:33:41.915739+09</val> +
</foo> +
+
(1 row)
与上面相同,但将 tableforest 设置为 false
postgres=# SELECT table_to_xml('foo'::regclass, true, false, '');
table_to_xml
-------------------------------------------------------------
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
+
<row> +
<id>1</id> +
<val>2023-09-18 19:33:41.91568+09</val> +
</row> +
+
<row> +
<id>2</id> +
<val>2023-09-18 19:33:41.915739+09</val> +
</row> +
+
</foo> +
(1 row)
nulls 设置为 true 和 false 时的行为
postgres=# UPDATE foo SET val = NULL;
UPDATE 2
postgres=# SELECT table_to_xml('foo'::regclass, true, true, '');
table_to_xml
-------------------------------------------------------------
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
<val xsi:nil="true"/> +
</foo> +
+
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
<val xsi:nil="true"/> +
</foo> +
+
(1 row)
postgres=# SELECT table_to_xml('foo'::regclass, false, true, '');
table_to_xml
-------------------------------------------------------------
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
</foo> +
+
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
</foo> +
+
(1 row)
指定 targetns 的值
postgres=# SELECT table_to_xml('foo'::regclass, true, true, 'foo');
table_to_xml
-------------------------------------------------------------------------
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="foo">+
<id>1</id> +
<val xsi:nil="true"/> +
</foo> +
+
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="foo">+
<id>2</id> +
<val xsi:nil="true"/> +
</foo> +
+
(1 row)
参考资料
- PostgreSQL 文档: 将表映射到 XML
