Iaroslav Baranov
Iaroslav Baranov

Reputation: 1120

Get default namespace from XMLDocument in JS

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()?

Upvotes: 0

Views: 1225

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

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.

Upvotes: 1

Related Questions