0

I loaded XMLDocument with XMLHttpRequest.

<root xmlns="http://somesite.org/ns">
</root>

http://somesite.org/ns is the default namespace. I can use function Node.isDefaultNamespace for check if some namespace is default (true/false) and it's work well.

But how can I get default namespace from XMLDocument?

Is there somethink like DOMString Node.getDefaultNamespace()?

0

1 Answer 1

1

Use lookupNamespaceURI(null):

var parser = new DOMParser();
[
  '<root xmlns="http://example.com/ns1"/>',
  '<root/>',
  '<ns:root xmlns:ns="example.com/ns2"/>'
].forEach(function(item) {
  var doc = parser.parseFromString(item, "application/xml");
  console.log('result of doc.lookupNamespaceURI(null): |' + doc.lookupNamespaceURI(null) + '|');
});

According to https://www.w3.org/TR/dom/#dom-node-lookupnamespaceuri, it should also work to use lookupNamespaceURI(''):

var parser = new DOMParser();
['<root xmlns="http://example.com/ns1"/>',
 '<root/>',
 '<ns:root xmlns:ns="example.com/ns2"/>'].forEach(function(item) {
  var doc = parser.parseFromString(item, "application/xml");
  console.log('result of doc.lookupNamespaceURI(\'\'): |' + doc.lookupNamespaceURI('') + '|');
});

Keep in mind that XML allows you to override the default namespace on any element so the result of doc.lookupNamespaceURI('') checks the documentElement and there can be children or descendants using a different or no default namespace.

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

9 Comments

It doesn't work. >myXML #document <root xmlns=​"http:​/​/​www.w3.org/​TR/​html77/​">​</root> ​>myXML.lookupNamespaceURI('') null
My answer contains an executable code snippet which works fine for me in current versions of Edge, Chrome, Firefox and IE on Windows 10. So in which environment have you run your code which does return null?
On Chrome/OS X, only doc.lookupNamespaceURI(null) works which is also what MDN says.
w3.org/TR/dom/#dom-node-lookupnamespaceuri specifies "If prefix is the empty string, set it to null. " in the algorithm for that method. But it looks as you are right on Chrome, somehow in my previous test I overlooked that the snippet shows null. I will edit the answer.
Seems to be a new feature in DOM4. This sentence is missing from the DOM Level 3 spec.
|

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.