2

I'm trying to use a UDF to parse my xml document. If I run the following, it works:

select xpath_string('<Application><applicationId>test</applicationId></Application>', '//applicationId') as id 
from my_table limit 2;

output is:

OK
test
test

If now I run the following code but add a namespace, I won't be able to parse my XML:

select xpath_string('<Application xmlns="http://domain.com/test"><applicationId>test</applicationId></Application>', '//applicationId') as id 
from my_table limit 2;

I will only get empty strings.

Is there anything that I am doing wrong? Or should I improve my XPath?

Thanks!

Stephane Maarek
  • 5,202
  • 9
  • 46
  • 87

1 Answers1

4

The 2nd XML introduces default namespace, which affect not only the element where default namespace is declared but also all descendant elements without prefix, including applicationId element :

xmlns="http://domain.com/test"

Commonly, you need to map a prefix, say d, to the default namespace uri and use that prefix in the XPath : //d:applicationId. I'm not familiar with the technology that you use, so not sure how and whether this approach is supported.

The following is a pure XPath 1.0 alternative :

//*[local-name()='applicationId' and namespace-uri()='http://domain.com/test']

or ignoring the namespace if you like :

//*[local-name()='applicationId']
har07
  • 88,338
  • 12
  • 84
  • 137
  • out of curiosity, why for other namespaces when not default, I could do d:applicationId, but the parser isn't smart enough when the namespace isn't specified, to just imply the default one? – Stephane Maarek May 02 '16 at 07:00
  • 1
    See the explanation [here](http://stackoverflow.com/a/21149866/2998271). That thread is about simplexml, which behave the same as you explained: it implies namespaces only for non-default namespace – har07 May 02 '16 at 07:04
  • insightful thanks. Best would be to recommend the people providing my xml to explicitely add a letter for the namespace. That would heavily simplify my xpath queries – Stephane Maarek May 02 '16 at 07:09