XML namespace trouble and possible work-around

2 views
Skip to first unread message

Elit

unread,
Jun 22, 2009, 5:07:40 PM6/22/09
to Prototype: Core
Earlier today I ran into a little problem.
I have this XHTML page which I create with an XML/XSL transformation.
When the page is loaded, I tried to add an element to it using
prototype's 'new Element()'. That created an element which I could add
to the page, but after that I could not get a reference to it with the
$() function, nor could I call new Element().update() because
apparently the object didn't get extended. (This occured in Firefox 3
and Safari 3.2. using prototype 1.6.1_rc3, IE 6 & 8 worked as
expected)

I found out that the element got added with an empty xmlns attribute
and I concluded that it was a namespace issue. I tried fixing it by
calling 'new Element(tagname, { xmlns: 'http://www.w3.org/1999/
xhtml'}) to match my document's namespace, but that didn't solve the
problem. I ended up tweaking the Element function so it would use
document.createElementNS if needed and available (IE doesn't support
it, but luckily doesn't need it either.)

global.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
var ns = attributes.xmlns || false; // ADDED
if (ns) delete attributes.xmlns; // ADDED
if (SETATTRIBUTE_IGNORES_NAME && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
if(ns && document.createElementNS) { // ADDED
return Element.writeAttribute(document.createElementNS(ns,
tagName), attributes);
}
return Element.writeAttribute(document.createElement(tagName),
attributes);
}
if (!cache[tagName]) {
if(ns && document.createElementNS) { //ADDED if/else
cache[tagName] = Element.extend(document.createElementNS(ns,
tagName));
}
else {
cache[tagName] = Element.extend(document.createElement
(tagName));
}
}
return Element.writeAttribute(cache[tagName].cloneNode(false),
attributes);
};


So, if I now call new Element(tagName, { xmlns: 'http://www.w3.org/
1999/xhtml'}) everything works as expected, and nothing seems broken
(If I had a nickel every time I heard that hehe)

Don't know if you want to or should add this to Prototype, but I
thought I'd just post it in case someone runs into the same problem.

Richard Quadling

unread,
Jun 23, 2009, 4:08:18 AM6/23/09
to prototy...@googlegroups.com
2009/6/22 Elit <elitb...@gmail.com>:
For the majority, should the namespace be defaulted to
'http://www.w3.org/1999/xhtml' if it is not supplied?

My thinking is if this is the default namespace, then the default
namespace should be used when using new Element().

Maybe?



--
-----
Richard Quadling
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
"Standing on the shoulders of some very clever giants!"
Reply all
Reply to author
Forward
0 new messages