8

I am finding that, for my purposes, XML namespaces are simply causing much headache and are completely unnecessary. (For example, how they complicate xpath.)

Is there a simple way to remove namespaces entirely from an XML document?

(There is a related question, but it deals with removing namespace prefixes on tags, rather than namespace declarations from the document root: "Easy way to drop XML namespaces with javascript".)

Edit: Samples and more detail below:

XML:

<?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>

JavaScript:

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

The sample XML is just like the actual one I am working with, albeit much shorter. Notice that there are no prefixes on the tags for the namespace. I assume this is the null or default namespace.

The JavaScript is a snippet from my ajax functions. If I remove the xmlns="example.com" portion from the main tag, I am able to successfully get the value. As long as any namespace is present, the value becomes undefined.

Edit 2:

It may be worth mentioning that none of the declared namespaces are actually used in the XML tags (like the sample above). In the actual XML file I am working with, three namespaces are declared, but no tags are prefixed with a namespace reference. Thus, perhaps the question should be re-titled, "How to remove unused XML namespaces using Javascript?" I do not see the reason to retain a namespace if it is 1) never used and 2) complicating an otherwise simple path to a node using xpath.

20
  • Namespaces are of no value, right up until they are needed. Commented Dec 22, 2010 at 0:53
  • The irony here is that namespaces were apparently developed to allow duplicate tags and avoid confusion between them. I have duplicate tags with differing parent tags, and am attempting to use xpath to select them. If I remove the namespace declaration manually, it's quite simple to select the elements. With the namespace declaration intact, it fails entirely. Commented Dec 22, 2010 at 1:02
  • 2
    Why not ask for help with using namespaces instead of giving up? Commented Dec 22, 2010 at 2:42
  • Namespaces shouldn't complicate xpath particularly, you just namespace the parts inside the xpath as you go. Maybe it would be better to figure out why your xpath isn't working, rather than stripping out structural data? Commented Dec 22, 2010 at 3:16
  • "but it deals with removing namespaces on tags, rather than from the entire document" - can you explain the difference? Do you mean you want to remove namespace declarations? Namespace prefixes? What does it mean to remove namespaces from an entire document other than removing them from tags? Commented Dec 22, 2010 at 4:19

3 Answers 3

6

This should remove any namespace declaration you find:

var xml = http.responseXML.replace(/<([a-zA-Z0-9 ]+)(?:xml)ns=\".*\"(.*)>/g, "<$1$2>");
Sign up to request clarification or add additional context in comments.

7 Comments

Results in Javascript console error: http.responseXML.replace is not a function.
@JY: you could force this to work by converting responseXML to a string before calling the replace() method. But it's not robust, since you're not really parsing the XML. @andre: are you sure that regex is correct? Can you explain the [a-zA-Z0-9 ]+?
That regex is correct. The part that you mention simply grabs the tag name and the space that follows, so, in <rootnode xmlns="some.domain.name" attribute="value"> it would replace it with <rootnode attribute="value">.
@LarsH: Converting it to a string is certainly an option, to make the replace function work. However, it would need to be converted back to XML. I need suggestions on how to do that (recreate the XML document with some sort of string parse?).
@andre: it looks to me like you want the space to be after the ]+, not intermixed multiple times with the alphanumerics of the tag name. Also the regex would at best replace only a default namespace declaration, not all namespace declarations. But that may be all that @JYelton needs...
|
4

Inorder to replace all the xmlns attributes from an XML javascript string

you can try the following regex

xmlns=\"(.*?)\"

NB: This regex can be used to replace any attributes

var str = `<?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>`;

str = str.replace(/xmlns=\"(.*?)\"/g, '');

console.log(str)

Comments

0

Approach without using regex (This removes attributes also)

let xml = '';//input
let doc = new DOMParser().parseFromString(xml,"text/xml");
var root=doc.firstElementChild;
var newdoc = new Document();
newdoc.appendChild(removeNameSpace(root));
function removeNameSpace (root){    
    let parentElement = document.createElement(root.localName);
    let nodeChildren = root.childNodes;
    for (let i = 0; i <nodeChildren.length; i++) {
        let node = nodeChildren[i];
        if(node.nodeType == 1){
            let child
            if(node.childElementCount!=0)
                child = removeNameSpace(node);
            else{
                child = document.createElement(node.localName);
                let textNode = document.createTextNode(node.innerHTML);
                child.append(textNode);
            }
            parentElement.append(child);
        }
    }
    return parentElement;
}

Comments

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.