Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to remove XML namespaces using Javascript?
    text
    copied!<p>I am finding that, for my purposes, XML namespaces are simply causing much headache and are completely unnecessary. (For example, how they complicate xpath.)</p> <p>Is there a simple way to remove namespaces entirely from an XML document?</p> <p>(There is a related question, but it deals with removing namespace prefixes on tags, rather than namespace declarations from the document root: "<a href="https://stackoverflow.com/questions/3704466/easy-way-to-drop-xml-namespaces-with-javascript">Easy way to drop XML namespaces with javascript</a>".)</p> <p><strong>Edit:</strong> Samples and more detail below:</p> <p><strong>XML:</strong></p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;main xmlns="example.com"&gt; &lt;primary&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/primary&gt; &lt;secondary&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/secondary&gt; &lt;/main&gt; </code></pre> <p><strong>JavaScript:</strong></p> <pre><code>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; } </code></pre> <p>The sample XML is just like the actual one I am working with, albeit much shorter. Notice that there are <em>no</em> prefixes on the tags for the namespace. I assume this is the null or default namespace.</p> <p>The JavaScript is a snippet from my ajax functions. If I remove the <code>xmlns="example.com"</code> portion from the <code>main</code> tag, I am able to successfully get the value. As long as any namespace is present, the value becomes undefined.</p> <p><strong>Edit 2:</strong></p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload