I'm using YQL to try and find band photos for a project I'm working on. If an image is found, it is r开发者_运维知识库eturned in an XML response, and my flash code posts it. But if one is not found, I'm not quite sure how to tell flash not to do anything. Here's my code:
XML.ignoreWhitespace = true;
var groupPhotoXML = new XML (e.target.data);
var imgRef = groupPhotoXML.results.img[0].@src;
if (imgRef != undefined){
//DO STUFF. THIS IF STATEMENT DOESN'T WORK THOUGH. ALSO TRIED if(groupPhotoXML != undefined)
}
Here's what a successful grouPhotoXML response looks like:
<query yahoo:count="1" yahoo:created="2011-07-13T16:35:21Z" yahoo:lang="en-US" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng">
<results>
<img alt="Syn photo" id="artistArtistImg" src="http://d.yimg.com/ec/image/v1/artist/266256;encoding=jpg;size=156x94" title="Syn photo"/>
</results>
</query>
An unsuccessful attempt traces out as empty.
Before you attempt to extract the src
attribute you should check to see if the results
and img
elements exist. Try doing this:
var imgRef:String;
if(groupPhotoXML.results && groupPhotoXML.results.img[0])
imgRef = groupPhotoXML.results.img[0].@src;
else
// The response was invalid
You might get the right node when the traces are empty, but you need to use toXMLString() to see it.
You can either check if the img node is present by checking the length of the XMLList:
if(groupPhotoXML.results.img.length() > 0) trace('do something with the img nodes');
or, if you only need img nodes that do not have an empty src attribute, you can check for an empty string like @taskinoor suggests, or by checking the length of @src:
imgs:XMLList = groupPhotoXML.results.img;
for each(var img:XML in imgs) if(img.@src.toXMLString().length > 0) trace('valid node',img.@src.toXMLString());
精彩评论