4

I've been trying to extract values from XML the same way as @Erwin Brandstetter answered a few times with an accepted answer, but it just doesn't work for me:

According to this post and this post this should work, but I just get an empty result:

WITH x AS ( SELECT
   '<Attributes xmlns="http://www.gis34.dk">
        <bemaerkning displayName="Bemærkning">Beatrix</bemaerkning>
        <billede displayName="Billede">https://vignette.wikia.nocookie.net/killbill/images/3/39/The_Bride.jpg</billede>
    </Attributes>'::xml AS t
)

SELECT xpath('/Attributes/bemaerkning/text()', t) as comment
FROM   x

Result: (expected: {My comment})

comment
xml[]
-------
{}

My database version:

PostgreSQL 9.1.3 on x86_64-unknown-linux-gnu, compiled by gcc-4.5.real (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2, 64-bit

Anyone has an idea?

2
  • check this one : stackoverflow.com/questions/17799790/… Commented Jan 29, 2016 at 9:20
  • @har07, this link was one of the two references in my question... :-) Commented Jan 29, 2016 at 9:28

1 Answer 1

7

Your XML defines a namespace, and that namespace must be used in the xpath expression.

SELECT xpath('/g:Attributes/g:bemaerkning/text()', t, array[array['g','http://www.gis34.dk']]) as comment
FROM   x

Note the third parameter that passes a two-dimensional array of namespace mappings.

The xpath() function returns an array of elements. If you know you only get a single element (or only ever want the first one) you just return the first element of the array:

SELECT (xpath('/g:Attributes/g:bemaerkning/text()', t, array[array['g','http://www.gis34.dk']])[1] as comment
FROM   x

Note the parentheses around the function call: (xpath(...))

Sign up to request clarification or add additional context in comments.

2 Comments

That's great. One more thing, is it possible to retrieve the text without the curly braces surrounding them?
@Ambran: xpath() returns an array, just use the first element. See my edit

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.