Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all namespace declarations of a single XML element

Tags:

xml

xpath

xquery

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>
like image 577
ivanacorovic Avatar asked Oct 23 '18 00:10

ivanacorovic


1 Answers

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)), "|")
like image 162
Mads Hansen Avatar answered Sep 28 '22 19:09

Mads Hansen