query_to_xml() 是一个用于将查询结果映射到 XML 的系统函数。
query_to_xml() 在 PostgreSQL 8.3 中引入。
用法
query_to_xml (querytext,nullsboolean,tableforestboolean,targetnstext)
→xml
query 是要转换为 XML 的 PostgreSQL 查询。请注意,如果提供 NULL,则函数将返回 NULL。
nulls,当设置为 true 时,将在输出中以以下方式表示 NULL 值:
<columnname xsi:nil="true"/>
如果 nulls 设置为 false,则 NULL 值将从输出中省略。
tableforest,当设置为 true 时,每个列集都将包装在一个 <table> 元素中;当设置为 false 时,每个列集都将包装在一个 <row> 元素中,该元素包含在一个外部 <table> 元素中。
targetns 指定结果的 XML 命名空间。如果提供空字符串,则不使用命名空间。请注意,如果提供 NULL,则函数将返回 NULL。
变更历史
- PostgreSQL 8.3
- 已添加 (commit 355e05ab)
示例
query_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 query_to_xml('SELECT * FROM foo', true, true, '');
query_to_xml
-------------------------------------------------------------
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
<val>2023-09-18 19:33:41.915739+09</val> +
</row> +
+
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
<val>2023-09-18 19:33:41.91568+09</val> +
</row> +
+
(1 row)
与上面相同,但将 tableforest 设置为 false
postgres=# SELECT query_to_xml('SELECT * FROM foo', true, false, '');
query_to_xml
---------------------------------------------------------------
<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
+
<row> +
<id>2</id> +
<val>2023-09-18 19:33:41.915739+09</val> +
</row> +
+
<row> +
<id>1</id> +
<val>2023-09-18 19:33:41.91568+09</val> +
</row> +
+
</table> +
(1 row)
将 nulls 设置为 true 和 false 时的行为
postgres=# UPDATE foo SET val = NULL;
UPDATE 2
postgres=# SELECT query_to_xml('SELECT * FROM foo', true, true, '');
query_to_xml
-------------------------------------------------------------
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
<val xsi:nil="true"/> +
</row> +
+
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
<val xsi:nil="true"/> +
</row> +
+
(1 row)
postgres=# SELECT query_to_xml('SELECT * FROM foo', false, true, '');
query_to_xml
-------------------------------------------------------------
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>2</id> +
</row> +
+
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+
<id>1</id> +
</row> +
+
(1 row)
为 targetns 指定值
postgres=# SELECT query_to_xml('SELECT * FROM foo', true, true, 'foo');
query_to_xml
-------------------------------------------------------------------------
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="foo">+
<id>2</id> +
<val xsi:nil="true"/> +
</row> +
+
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="foo">+
<id>1</id> +
<val xsi:nil="true"/> +
</row> +
+
(1 row)
参考资料
- PostgreSQL 文档: 将表映射到 XML
