ivanacorovic
ivanacorovic

Reputation: 2867

How to get all namespace declarations of a single XML element

How can I use XPath query (or even XQuery) to get nampespace prefix declaration of a single element? I want to check if they get defined on more than 1 place.

For example, for the first element, it would be xmlns and xmlns:n, for the second only xmlns; for the first < n:int> it would be nothing, etc.

I can only find these I can get only namespaces in use, but not really what I'm looking for.

<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <plus xmlns="http://lalaivana.me/calc/"
            xmlns:n="http://lalaivana.me/numbers/" >
            <n:int value="4"/>
            <n:int value="5"/>
        </plus>
        <plus xmlns="http://lalaivana.me/calc/">
            <int value="4" xmlns="http://lalaivana.me/numbers/" />
            <int value="5"/>
        </plus>
    </root>

Upvotes: 7

Views: 1418

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66723

You can use the functions in-scope-prefixes() and namespace-uri-for-prefix() in order to obtain the namespace-prefix and the namespace-uri for the in-scope namespaces bound to an element.

for $element in $doc//*
return 
  for $prefix in fn:in-scope-prefixes($element)
  return string-join( (name($element), $prefix,fn:namespace-uri-for-prefix($prefix, $element) ), "|")

Note that the XML namespace http://www.w3.org/XML/1998/namespace will be included with the prefix xml. You can exclude it with a predicate filter:

for $element in $doc//*:plus[2]
return 
  for $prefix in fn:in-scope-prefixes($element)[not(. eq 'xml')]
  return string-join((name($element), $prefix,fn:namespace-uri-for-prefix($prefix, $element)), "|")

Upvotes: 4

Related Questions