我在 PostgreSQL 中创建了一个表,其中包含一个 XML 列。我正在为该列使用 text
数据类型。现在我有一个示例 XML,它存储在一个字段中,如下表所示:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
现在我已经创建了一个程序来比较 2 个 XML 数据。如果找到 XML 数据,则返回 true 否则返回 false
问题是如果 XML 数据存储在表中的一行中
<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
然后它给出所需的输出,但如果它存储在不同的行中,则返回 null
。
我的程序如下所示
CREATE OR REPLACE FUNCTION comparexml(p_name_in VARCHAR(255), p_xml_data_in text, out p_id integer)AS $BODY$
DECLARE
V_ID INTEGER;
BEGIN
SELECT id INTO v_id
FROM employee
WHERE XML_DATA = p_xml_data_in and
NAME=p_name_in;
IF(v_id IS NULL) THEN
V_ID := 0;
ELSE
V_ID := 1;
END IF;
p_id=v_id;
END;
$BODY$ LANGUAGE plpgsql;
最佳答案
我不确定您为什么关心一个 XML 文档是否与另一个相同。如果您使用此限定条件进行搜索,您可能(但不一定)做错了。这不是 XML 的用途。您可以搜索 XML 中某物的存在..
CREATE TABLE foo AS SELECT xmlparse(DOCUMENT xml) AS xmlcol
FROM ( VALUES
($$<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
$$),
($$ <note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note> $$)
) AS t(xml);
但是你不应该关心是否 foo.xmlcol = p_xml_data_in
。试试看
- table 上的一个 id。
- xml 中的一个 id。
就是说,如果这对您很重要,您也许可以 bribe the guy who write this answer and committed the xml code . PostgreSQL 当前没有 canonicalxml
类型,但可以实现,并且在 TODO 上(并且可能会在那里停留很长时间)
XML Canonical: Convert XML documents to canonical form to compare them. libxml2 has support for this.
关于xml - 如何在 PostgreSQL 中比较 XML 的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41358900/