How to use jQuery for XML parsing with namespaces
I got it.
Turns out that it requires \\
to escape the colon.
$.get(xmlPath, {}, function(xml) {
$("rs\\:data", xml).find("z\\:row").each(function(i) {
alert("found zrow");
});
}, "xml");
As Rich pointed out:
The better solution does not require escaping and works on all "modern" browsers:
.find("[nodeName=z:row]")
How to parse xml with namespaces using JQuery (and working for all browser .. )?
You can iterate through the XML elements using jQuery and find()
, just like with HTML. When specifying tag names to select, you need to omit the namespace prefix in the selector.
var xmlText = $('#featureData').text(),
$xmlData = $.parseXML(xmlText),
$features = $('featureMember', $xmlData),
extractedFeatures = [];
$features.each(function () {
var $this = $(this),
feature = {},
items = [
'nome',
'civico',
'istat',
'cap',
'comune'
],
item;
for (var i = 0; i < items.length; i++) {
item = items[i];
feature[item] = $this.find(item).text();
}
extractedFeatures.push(feature);
});
$('#output').text(JSON.stringify(extractedFeatures));
See the jsFiddle reproduction here
Parsing XML with namespaces using jQuery $().find
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
$(this).find("geo\\:lat").text();
Parsing xml namespace with jQuery. Help needed!
I recommend using a real namespace-aware XML parser if at all possible, especially when dealing with external services. There is no guarantee that the namespace prefix will remain constant over time, for example.
Most JavaScript DOM parsers will include getElementsByTagNameNS()
, which will let you find elements with the actual namespace.
The process might look something like this, assuming your data was in xml_file
.
var namespace = 'http://aws.example.com/';
var parser = new DOMParser(); // Webkit, IE has its own
var xml = parser.parseFromString(xml_file, "text/xml");
var year = xml.getElementsByTagNameNS(namespace, 'year')[0]; // returns the first aws:year element
var year_value = year.getAttribute('number');
Parse xml with namespaces using JQuery and working for all browser ..
You have to be careful with namespaces... if you work with XML that has some namespaces declaration you have to keep it in mind and build appropriate selectors.
For example:
$features = $('gml\\:featureMember, featureMember', $xmlData),
Please take a look on update fiddle. Now it works in FF and IE as well.
Parsing XML JQuery Ajax Response with Namespace
When an element is prefixed by a namespace, you have to also add the namespace:
.find('ns1:return')
does not work, because:
is used by jQuery as pseudo-selectors..find('ns1\:return')
does not work either, because a single backslash in a string is used as an escape character."ns1\:return"
becomes"ns1:return"
which is equal to the previous one..find('ns1\\:return')
should be used. The double backslash is used to escape the colon.
It appears that the last solution works fine in IE and Firefox, but not Opera, Chrome or Safari. To get maximum compatibility, use jQuery selectors with, and without fake prefix, ie. "ns1\\:return, return"
instead of a plain ns1\\:return
.
Demo: http://jsfiddle.net/5BQjv/51/
// For example, this is the result:
var data = '<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">' +
'<ns1:return>' +
'<results> <row> ... </row> </results>' +
'</ns1:return>' +
'</ns1:executeResponse>';
// The very first thing is to parse the string as XML. NOT later!
var $xmlDoc = $($.parseXML(data));
// Then, look for the element with the namespace:
var $txt = $xmlDoc.find('ns1\\:return, return');
// No need to use unescape or something, just use DOM manipulation:
// `results` is the immediate child. Don't use .find, but .children
var $firstrow = $txt.children("results").children(":first");
As you may have noticed, I have prefixed some variables with a dollar sign. It's the convention to prefix variables which refer to jQuery objects with a dollar sign, to avoid confusion during/after development.
Finding an XML node by namespace with jQuery
You can use the attribute-contains jQuery-selector (see here)
xml.find("[nodeName*='x:']")
Parse XML Node Values With Colon Using jQuery
Answer can be found in the comment by Dave Newton
Related Topics
How to Access Iframe Elements with JavaScript
Variable === Undefined VS. Typeof Variable === "Undefined"
How to Mock Functions in the Same Module Using Jest
Javascript: Setting Location.Href Versus Location
Identifying Between Refresh and Close Browser Actions
Why Doesn't Equality Check Work with Arrays
JavaScript - Href VS Onclick for Callback Function on Hyperlink
Es6 Modules: Export Single Class of Static Methods or Multiple Individual Methods
Facebook Social Plug-In Not Showing Up When Added Dynamically
Convert Base64 String to Arraybuffer
Truncate Number to Two Decimal Places Without Rounding
Explanation of <Script Type = "Text/Template"> ... </Script>
Async/Await Always Returns Promise
Asynchronous for Cycle in JavaScript
Check Whether Variable Is Number or String in JavaScript
What Is Typescript and Why Would I Use It in Place of JavaScript