Reputation: 2816
i am new with ajax. I have done normal xml parsing via jquery but can not get the xml with namespace working. I have searched the web and there is very few resources i found. Here is a post in stackoverflow but it is not working for me.
jQuery XML parsing with namespaces
Here is the part of the xml file. suppose i need the year number from the xml data. How i will get it?
<aws:sunset>
<aws:year number="2011" />
<aws:month number="3" text="March" abbrv="Mar" />
<aws:day number="27" text="Sunday" abbrv="Sun" />
<aws:hour number="7" hour-24="19" />
<aws:minute number="10" />
<aws:second number="28" />
<aws:am-pm abbrv="PM" />
<aws:time-zone offset="-5" text="Central Daylight Time (USA)" abbrv="CDT" />
</aws:sunset>
Waiting for your reply. Thanks!
Upvotes: 1
Views: 4013
Reputation: 2963
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');
Upvotes: 6
Reputation: 6526
You can parse the DOM when you use double backslash to escape the colon
ex.
$("aws\\:year").attr('number')
edit:
the solution above does not work with webkit browsers. better solution
$("[nodeName=aws:year]").attr('number')
didn't check this out though.
Upvotes: 0