Easy way to drop XML Namespaces with JavaScript?

半腔热情 提交于 2019-12-10 14:29:41

问题


Is there an easy way, for example, to drop an XML name space, but keep the tag as is with jQuery or JavaScript? For example:

<html:a href="#an-example" title="Go to the example">Just an Example</html:a>

And change it to:

<a href="#an-example" title="Go to the example">Just an Example</a>

On the fly with jQuery or JavaScript and not knowing the elements and or attributes inside?


回答1:


If there is no <script> tag in the code to be replaced you can try (demo):

container.innerHTML = container.innerHTML
                               .replace(/<(\/?)([^:>\s]*:)?([^>]+)>/g, "<$1$3>")



回答2:


This isn't really an answer, but you'd be better off handling this server-side. JavaScript comes into the picture a bit too late for this kind of task... events may have already been attached to the existing nodes and you'd be processing each element twice.

What is the purpose of the namespace?

If these are static html files and the namespace serves no purpose I would strip all the namespaces with a regex.

If they're not static and the namespace has a purpose when served as xml, you could do some server-side detection to serve with the right doctype and the namespace (when appropriate).




回答3:


It's easy when you know how ... just use \\ to escape the colon so it's not parsed as an action delimiter by the jquery parsing engine.

$('html\\:a').each( function(){
  var temp = $(this).html();
  $(this).replaceWith("<a>"+temp+"</a>");
});

This should iterate between each of those elements and replace them with normal tags. Since these are being served up to an ajax callback function, otherwise I don't see why you'd want to do it on the fly ... then the top line would change to:

$.post('...',{}, function(dat){
    $(dat).find('html\\:a').each( blah blah ....
    .
    .
});

NB, i'm one of those terrible people who only really tests things in FF ...



来源:https://stackoverflow.com/questions/3704466/easy-way-to-drop-xml-namespaces-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!