How to get all namespace declarations of a single XML element
Asked Answered
A

1

7

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>
Amalekite answered 23/10, 2018 at 0:50 Comment(0)
E
4

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)), "|")
Eadie answered 23/10, 2018 at 3:39 Comment(2)
That would be fine if I wanted all in scope prefixes, but I only want the ones defined on the element, I don't care about ones defined on its parents. It's funny how there is no prefix-related function that will give me that.Amalekite
You don’t have that information available after the XML has been parsed. You will need to use an API, such as SAX to respond to the parse events and collect that information.Eadie

© 2022 - 2024 — McMap. All rights reserved.