PostgreSQL中含xmlns的XML文档guid字段提取问题
解决带默认命名空间的XML中提取guid字段的问题
你的SQL返回空值的核心原因是:XML中存在默认命名空间(xmlns="http://zakupki.gov.ru/223fz/types/1"),而原XPath查询没有指定对应的命名空间,导致无法匹配到目标节点。
下面提供两种可行的解决方法:
方法一:绑定命名空间前缀(推荐,规范严谨)
在XMLTABLE中通过namespaces子句为默认命名空间绑定一个前缀(比如t),然后在XPath中使用该前缀定位节点:
with XML_text(col) as ( select '<?xml version="1.0" encoding="UTF-8"?> <purchasePlan xmlns:ns2="http://zakupki.gov.ru/223fz/purchasePlan/1" xmlns="http://zakupki.gov.ru/223fz/types/1" xmlns:ns10="http://zakupki.gov.ru/223fz/decisionSuspension/1" xmlns:ns11="http://zakupki.gov.ru/223fz/disagreementProtocol/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://zakupki.gov.ru/223/integration/schema/TFF-13.1 https://zakupki.gov.ru/223/integration/schema/TFF-13.1/purchasePlan.xsd"> <body> <item> <guid>096c4bf6-d656-4441-9032-0b7c45423af1</guid> </item> </body> </purchasePlan>'::xml ) SELECT r.guid FROM XML_text as x, XMLTABLE('t:purchasePlan/t:body/t:item' passing x.col namespaces ('http://zakupki.gov.ru/223fz/types/1' as t) COLUMNS guid varchar(50) path './t:guid' ) as r;
方法二:忽略命名空间(简单场景可用,不够严谨)
使用XPath的local-name()函数匹配节点的本地名称,跳过命名空间校验:
with XML_text(col) as ( select '<?xml version="1.0" encoding="UTF-8"?> <purchasePlan xmlns:ns2="http://zakupki.gov.ru/223fz/purchasePlan/1" xmlns="http://zakupki.gov.ru/223fz/types/1" xmlns:ns10="http://zakupki.gov.ru/223fz/decisionSuspension/1" xmlns:ns11="http://zakupki.gov.ru/223fz/disagreementProtocol/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://zakupki.gov.ru/223/integration/schema/TFF-13.1 https://zakupki.gov.ru/223/integration/schema/TFF-13.1/purchasePlan.xsd"> <body> <item> <guid>096c4bf6-d656-4441-9032-0b7c45423af1</guid> </item> </body> </purchasePlan>'::xml ) SELECT r.guid FROM XML_text as x, XMLTABLE('*[local-name()="purchasePlan"]/*[local-name()="body"]/*[local-name()="item"]' passing x.col COLUMNS guid varchar(50) path '*[local-name()="guid"]' ) as r;
两种方法都能返回期望结果:096c4bf6-d656-4441-9032-0b7c45423af1
内容的提问来源于stack exchange,提问作者Дмитрий Мыльч
相关产品推荐
相关产品推荐

