如何在PostgreSQL中比较XML的相等性

时间:2016-12-28 09:18:32

标签: xml postgresql comparison

我在PostgreSQL中创建了一个包含XML列的表。我正在使用该列的getAddress { (address) in print(address) } 数据类型。现在我有一个样本XML存储在一个字段中,如下表所示:

text

现在我创建了一个比较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>

然后它给出了所需的输出,但如果它存储在不同的行中,则返回<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

我的程序如下所示

null

2 个答案:

答案 0 :(得分:0)

我不确定为什么你关心一个XML文档是否等于另一个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。试试

  • 桌上的id。
  • xml中的id。

那就是说,如果这对你很重要,你或许可以bribe the guy who write this answer and committed the xml code。 PostgreSQL当前没有canonicalxml类型,但它可以实现,它可以在TODO上进行(并且可能会在那里保留很长时间)

  

XML Canonical:将XML文档转换为规范形式以进行比较。 libxml2支持此功能。

答案 1 :(得分:-1)

plpythonlxml的帮助下,你可以清除一下你的xml:

CREATE OR REPLACE FUNCTION xmlclean(xml_doc text) RETURNS text AS
$BODY$

from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)

return etree.tostring(etree.XML(xml_doc, parser=parser))

$BODY$
LANGUAGE plpythonu;

样本用法:

postgres=# select xmlclean('<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don''t forget me this weekend!</body>
</note>');
                                                             xmlclean                                             
------------------------------------------------------------------------------------------------------------------
 <note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
(1 row)

postgres=# select xmlclean('<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don''t forget me this weekend!</body></note>');
                                                     xmlclean                                                     
------------------------------------------------------------------------------------------------------------------
 <note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
(1 row)

然而,它仍然不完美:如果标签顺序不同(我猜语义会保持不变,即它们应该被认为是相同的,但显然它们不会)

相关问题