We've got an XML file where some nodes are namespaced. Basically the file looks like this:
<foo>
<bar xmlns:x="http://www.example.com/">
<x:bla foo="bar" />
</bar>
</foo>
What we want to achieve is that we want to select the x:bla
node, but unfortunately we don't know in advance the node's name, just its namespace. Hence all we know is basically that it's a x:*
node.
Now, the question is: How do we select this node by using jQuery's find
method once we have parsed the XML file by using $.parseXML
?
Using $(xml).find("x\\:bla, bla")
works, but only if I know that the node is called bla
.
XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
As defined by the W3C Namespaces in XML Recommendation , an XML namespace is a collection of XML elements and attributes identified by an Internationalized Resource Identifier (IRI); this collection is often referred to as an XML "vocabulary."
The Namespace starts with the keyword xmlns. The word name is the Namespace prefix. The URL is the Namespace identifier.
An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.
You can use the attribute-contains jQuery-selector (see here)
xml.find("[nodeName*='x:']")
.parseXML()
is giving me XML parse error, it seems it can't handle the <x:bla..
syntax.
So I just used jQuery with a custom selector to find elements by namespace:
$.expr[':'].findNS = function(obj, idx, meta, stack) {
if (obj.nodeName.indexOf(meta[3].toUpperCase()+':') === 0) {
return true;
}
return false;
};
var xml="<foo><bar><x:bla atr='attvalue' /></bar></foo>";
alert( $(xml).find(':findNS(x)').attr('atr') ); // Alerts 'attvalue'
See working demo
jQuery XML parsing with namespaces shows how to search for a literal namespace prefix. I would consider this an "evil" workaround, because it's no real XML processing. But it looks like jQuery does not support any real namespace handling. So you probably have to go for that solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With