如何在 Postgres 11 和 Postgres 9.1.2 中解析 XML

How to parse XML in Postgres 11 and in Postgres 9.1.2

在 Postgres 9.1.2 中,下面的脚本会产生正确的结果:

1.34
5.56

在 Postgres 11 中它会产生错误的结果:

null
null

如何让它在 Postgres 的较新版本中也能工作?

create temp table t(x xml, nsa text[][]) on commit drop;
insert into t values(
    '<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
  <BkToCstmrStmt>
    <Stmt>
      <Ntry>
        <Amt Ccy="EUR">1.34</Amt>
      </Ntry>
      <Ntry>
        <Amt Ccy="EUR">5.56</Amt>
      </Ntry>
    </Stmt>
  </BkToCstmrStmt>
</Document> '::xml,
    ARRAY[ARRAY['ns','urn:iso:std:iso:20022:tech:xsd:camt.053.001.02']]);

    SELECT 
    (xpath('Amt/text()', x,nsa))[1]::text::numeric AS tasusumma
    FROM (
        SELECT unnest(xpath('/ns:Document/ns:BkToCstmrStmt/ns:Stmt/ns:Ntry', x,nsa)) as x,
        nsa
        FROM t
    ) Ntry

用它的命名空间别名来限定 Amt 就足够了:

SELECT (xpath('ns:Amt/text()', x, nsa))[1]::text::numeric AS tasusumma
FROM (
    SELECT unnest(xpath('/ns:Document/ns:BkToCstmrStmt/ns:Stmt/ns:Ntry', x, nsa)) as x,
    nsa
    FROM t
) Ntry;

我在 10.6 上测试过;我很确定它也适用于 11。它也适用于以前的版本(在 9.6 上测试)。