0

PostgreSQL 14. Trying to extract all the node names from xml element:

SELECT xpath('./*/name()', '<foo><bar>test</bar><zar>test1</zar></foo>')

does not work

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

works

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

offered as solution gives empty list.

example:

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

will work

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

will not

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

works

SELECT xpath('//name()', unnest(xpath('/foo/*', '<foo><bar>test</bar><zar>test1</zar></foo>')))::varchar

does not work what is wrong with name(), local-name(), namespace-uri() functions? How to get a list of nodes within Postgres without parsing it outside? thanks

2
  • What about using a regex? regexp_matches('<foo><bar>test</bar><zar>test1</zar></foo>', '(<[a-zA-Z]+>)', 'g'); Commented Mar 9, 2022 at 12:06
  • impossible in my case, i'm parsing quite complicated structure with xmltable and json object in one request. This simple example just to illustrate point. Commented Mar 9, 2022 at 12:24

2 Answers 2

1

It seems that this solution can bypass the problem. For some reason direct call of name() function is not working in xpath() function in latest versions of postgres.

SELECT * 
FROM xmltable('//*' PASSING '<foo><bar>text</bar></foo>'
            COLUMNS
            name varchar PATH 'name()'
            )
Sign up to request clarification or add additional context in comments.

Comments

0

This one works on Postgres 9.6. Please notice xpath is //*

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

Result

xpath
-----
{foo}
{bar}
{zar}

This XPath also works: /* | /*//*

10 Comments

SELECT x::varchar FROM (SELECT xpath('name()', unnest(xpath('//*', '<foo><bar>test</bar><zar>test1</zar></foo>'))) AS x) AS xt gives empty list in postgres 14
What do you get from SELECT unnest(xpath('//*', '<foo><bar>test</bar><zar>test1</zar></foo>'));?
``` xpath |===| |{""}| |{""}| |{""}| |---| ``` sorry for formatting
Please try the second posted xpath.
unnest | ------------------------------------------+ <foo><bar>test</bar><zar>test1</zar></foo>| <bar>test</bar> | <zar>test1</zar> |
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.