首页 > 解决方案 > Postgres 使用带有 xmlnamespaces 的 xpath_table 解析

问题描述

我可以使用xpath_tablexmlnamespaces 解析吗

drop table if exists _xml;
create temporary table _xml  (fbf_xml_id serial,str_Xml xml);

insert into _xml(str_Xml)
select  '<DataSet1  xmlns="http://tempuri.org/DataSet_LocalMaMC.xsd">
  <Stations>
    <ID>5</ID>
  </Stations>
  <Stations>
    <ID>1</ID>
  </Stations>
  <Stations>
    <ID>2</ID>
  </Stations>
  <Stations>
    <ID>10</ID>
  </Stations>
  <Stations>
    <ID/>
  </Stations>
  </DataSet1>' ;


drop table if exists _y;
create temporary table _y as
SELECT * 
FROM xpath_table('FBF_xml_id','str_Xml','_xml',
              '/DataSet1/Stations/ID',
              'true') AS t(FBF_xml_id int,ID text);
select * from _y

如果我采用 xmlnamespaces 它工作正常。我想使用 Xpath,但是当有 null 时,它会给我错误的结果。

标签: postgresqlxml-namespaces

解决方案


使用 Postgres 10 或更高版本,xmltable()是执行此操作的首选方法。

您可以使用它轻松指定命名空间列表。

SELECT fbf_xml_id, xt.id
FROM _xml
  cross join 
      xmltable(xmlnamespaces ('http://tempuri.org/DataSet_LocalMaMC.xsd' as x),
               '/x:DataSet1/x:Stations'
               passing str_xml
               columns 
                  id text path 'x:ID') as xt

请注意,在用于xmltable()函数的 XPath 表达式中,标记以xmlnamespaces选项中定义的命名空间别名为前缀,即使它们在输入 XML 中没有前缀。

在线示例


推荐阅读