Strange bug parsing XML with jQuery
Can anyone explain this strange behaviour in jQuery? I'm using version 1.5.2.
var myxml = '<photo><Point srsName="EPSG:4326"><coordinates>0.153933,52.204674</coordinates></Point><id>24917</id><latitude>52.204674</latitude><longitude>0.153933</longitude><feature>3</feature><caption>No parking.</caption><url>http://www.google.co.uk</url><imageUrl>http://www.google.co.uk</imageUrl><thumbnailUrl>http://www.google.co.uk</thumbnailUrl><thumbnailSizes>60|120|150|180|200|250|300|350|400|400|425|450|500|640</thumbnailS开发者_运维问答izes></photo>';
console.log($(myxml).find('latitude').text());
console.log($(myxml).find('caption').text());
latitude
prints the correct value, but caption
is an empty string.
I've tried using nodeName
as well, but I get the same result.
Any ideas? Thanks!
UPDATE: I've also made a jsFiddle to show the behaviour: http://jsfiddle.net/w8Z7z/
You aren't telling jQuery you're working with XML. caption
is an HTML tag and reserved word, so it is getting confused. You need to use $.parseXML():
var myxml = '...(all that xml)...',
xmlDoc = $.parseXML( myxml ),
$xml = $( xmlDoc );
console.log($xml.find('caption').text());
Caption
appear to be a reserved word. So, if yo use for example captionX
works.
Try with other nodeName.
var myxml = '<photo><Point srsName="EPSG:4326"><coordinates>0.153933,52.204674</coordinates></Point><id>24917</id><latitude>52.204674</latitude><longitude>0.153933</longitude><feature>3</feature><captionX>No parking.</captionX><url>http://www.google.co.uk</url><imageUrl>http://www.google.co.uk</imageUrl><thumbnailUrl>http://www.google.co.uk</thumbnailUrl><thumbnailSizes>60|120|150|180|200|250|300|350|400|400|425|450|500|640</thumbnailSizes></photo>';
console.log($(myxml).find('captionX').text());
console.log($(myxml).find('latitude').text());
If you parse the xml first and then pass that to jquery it works:
http://jsfiddle.net/w8Z7z/2/
var xmldoc=$.parseXML(myxml);
alert($(xmldoc).find('caption').text());
精彩评论