【问题标题】:Error extracting XML values in PostgreSQL using XPath: SQL Error [42601]: ERROR: syntax error at or near "["使用 XPath 在 PostgreSQL 中提取 XML 值时出错:SQL 错误 [42601]:错误:“[”处或附近的语法错误
【发布时间】:2018-05-07 07:55:52
【问题描述】:

我正在尝试使用 XPath 从存储在 PostgreSQL 数据库中的 XML 中提取值。我有一个错误:

SQL 错误 [42601]:错误:“[”处或附近的语法错误

我的 SQL 是:

-- Find "e" nodes which have "p1" child nodes and does not have "p3" child nodes
WITH tbl(p_xml) AS (
   SELECT '<root>
    <e id="1">
        <p1>P1</p1>
        <p2>P2</p2>
    </e>
    <e id="2">
        <p1>P1</p1>
        <p3>P2</p3>
    </e>
    <e id="3">
        <p2>P1</p2>
        <p3>P3</p3>
    </e>
</root>'::xml
)
select * 
FROM   tbl
where
    (xpath('count(/root/e/p1)', p_xml)[1]::text)::int > 0 and 
    (xpath('count(/root/e/p3)', p_xml)[1]::text)::int = 0

我在 StackOverflow 上看到了很多使用正方形获取数据的示例(因为 xpath 函数返回数组),但在我的 PostgreSQL 上所有这些示例都失败并出现相同的错误。我在 PostgreSQL DB 版本 9.6 和 10.1 上试过这个,但没有运气。

【问题讨论】:

    标签: xml postgresql xpath


    【解决方案1】:

    我对@9​​87654321@ 没有经验,但这似乎可行:

    where
        (xpath('count(/root/e/p1)', p_xml)::text[])[1]::int > 0 and 
        (xpath('count(/root/e/p3)', p_xml)::text[])[1]::int = 0
    

    看起来,好像xpath() 必须强制转换为字符串数组,您可以在其中选择第一个元素将其强制转换为int。不是很直观。

    可能有更好的方法...

    【讨论】:

      【解决方案2】:

      那是因为您的查询缺少括号。无论如何,如果您只想返回满足该条件的 e 元素,您需要粉碎 XML,例如:

      WITH tbl(p_xml) AS (
         SELECT '<root>
          <e id="1">
              <p1>P1</p1>
              <p2>P2</p2>
          </e>
          <e id="2">
              <p1>P1</p1>
              <p3>P2</p3>
          </e>
          <e id="3">
              <p2>P1</p2>
              <p3>P3</p3>
          </e>
      </root>'::xml
      )
      SELECT e
      FROM tbl
      CROSS JOIN LATERAL UNNEST(xpath('//e[p1 and not(p3)]', p_xml)) e
      

      rextester 演示:http://rextester.com/FZGP41665

      【讨论】:

      • 我知道,一定有更好的方法 :-)
      猜你喜欢
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 2020-03-15
      • 2021-01-17
      相关资源
      最近更新 更多