Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion - Check if XmlNode exists

I've really been struggling to find a solution to this. My code is different from what I've seen on a Google search, and nothing I've tried will work. Basically as the title suggests I want to check if an Xml Node exists. This is because of erratic XML returned from a YouTube feed. Code is below.

<cfset YouTubeXml = xmlParse(#YouTubeFavourites.FileContent#) />
<cfset group = XmlSearch(YouTubeXml, "//media:group") />    

<cfloop from="1" to="25" index="i">
    <cfoutput>
        #group[i]['media:thumbnail'][i]['url']#
    </cfoutput>
</cfloop>

Basically the error says that #group[i]['media:thumbnail'][i]['url']# doesn't exist. Hope someone can help.

like image 271
Douglas Avatar asked Mar 03 '26 03:03

Douglas


2 Answers

The below code will check to ensure the variable exists before it tries to display it. The nested approach is the only way to ensure each piece exists as you go along. There are functions to make it look prettier, but that's a topic for another question.

<cfset YouTubeXml = xmlParse( YouTubeFavourites.FileContent ) />
<cfset group = XmlSearch( YouTubeXml, "//media:group" ) />

<cfoutput>
<cfloop from="1" to="25" index="i">
    <cfif StructKeyExists( Group, i )
        AND StructKeyExists( Group[ i ], 'media:thumbnail' )
        AND StructKeyExists( Group[ i ][ 'media:thumbnail' ], i )
        AND StructKeyExists( Group[ i ][ 'media:thumbnail' ][ i ], 'url' )>
        #group[i]['media:thumbnail'][i]['url']#
    </cfif>
</cfloop>
</cfoutput>

I find it odd that you're using i twice in the variable name, but I'm not familiar with the Youtube API, so maybe that is correct.

I've changed two things in your code that weren't need. I removed the extra ## signs in xmlParse() as it's already going to be treated as a variable there. I also moved the <cfoutput> out of the loop, as there's a slight performance loss declaring <cfoutput> multiple times.

like image 132
Busches Avatar answered Mar 04 '26 21:03

Busches


Try using isDefined() ?

<cfset YouTubeXml = xmlParse(YouTubeFavourites.FileContent) />
<cfset group = XmlSearch(YouTubeXml, "//media:group") />

<cfloop from="1" to="25" index="i">
<cfif isDefined("#group[i]['media:thumbnail'][i]['url']#")>
    <cfoutput>
        #group[i]['media:thumbnail'][i]['url']#
    </cfoutput>
</cfif>
</cfloop>
like image 21
Michael Giovanni Pumo Avatar answered Mar 04 '26 22:03

Michael Giovanni Pumo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!