簡體   English   中英

如何在 Postgres 中使用 xpath 獲取元素的名稱

[英]How to get name of an element using xpath in Postgres

我試過這個

select xpath('name()', unnest(xpath('/foo/*', '<foo><bar>test</bar><zar>test1</zar></foo>')));

正如此處其他問題中所建議的那樣,但我只得到兩個空行作為響應。

另外我試過

select unnest(xpath('name(/foo/*)', '<foo><bar>test</bar><zar>test1</zar></foo>'));

但它只返回一行響應為bar

無論如何我可以讓查詢返回兩行結果bar , zar使用 Xpath 嗎?

如果輸出應該是行,我發現xmltable()更容易使用:

with data (content) as (
  values ('<foo><bar>test</bar><zar>test1</zar></foo>'::xml)
)  
select x.*
from data
  cross join xmltable('/foo/*' passing content
                       columns 
                         item text path 'name()', 
                         value text path '.') as x

輸出是:

item | value
-----+------
bar  | test 
zar  | test1

使用 xpath 函數text()提取元素的內容:

SELECT unnest(xpath('/foo/*/text()','<foo><bar>test</bar><zar>test1</zar></foo>'));

 unnest 
--------
 test
 test1
(2 Zeilen)

要列出元素名稱,請使用子查詢/CTE 或使用兩個unnest() ,例如

SELECT 
  unnest(xpath('local-name(./*)',
  unnest(xpath('/foo/node()', '<foo><bar>test</bar><zar>test1</zar></foo>'))));

 unnest 
--------
 bar
 zar
(2 Zeilen)

您可以使用name()函數來提取標簽名稱:

select xpath('name(/*)', x)
FROM unnest(
        xpath(
           '/foo/*',
           '<foo><bar>test</bar><zar>test1</zar></foo>'
        )
     ) AS xml(x);

 xpath 
═══════
 {bar}
 {zar}
(2 rows)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM