Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an XML node by namespace with jQuery

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.

like image 718
Golo Roden Avatar asked Nov 13 '12 09:11

Golo Roden


People also ask

How do I find the XML namespace?

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".

What is namespace node in XML?

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."

What is the URL in XML namespace?

The Namespace starts with the keyword xmlns. The word name is the Namespace prefix. The URL is the Namespace identifier.

How does namespace work in XML?

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.


3 Answers

You can use the attribute-contains jQuery-selector (see here)

xml.find("[nodeName*='x:']")
like image 110
Roberto Bez Avatar answered Oct 05 '22 07:10

Roberto Bez


.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

like image 22
Nelson Avatar answered Oct 05 '22 06:10

Nelson


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.

like image 21
Achim Avatar answered Oct 05 '22 07:10

Achim