Skip to main content
Known Participant
May 4, 2011
Answered

Parsing through an XML file

  • May 4, 2011
  • 2 replies
  • 622 views

Hi,

I'm working with an XML file that is generated through Google's Books API.  I'm going to apologize in advance if I don't get the XML terminology quite correct -- this is my first foray into some of the CF XML tags.  I'm reading an XML file in, and attempting to output some data:

<cfhttp url="http://www.google.com/books/feeds/volumes?q=john+grisham+the+firm&min-viewability=partial" method="GET">

<CFSET xmlfile = xmlparse(cfhttp.filecontent)>


<cfset xmlsize = arraylen(xmlfile.feed.entry)>


<cfloop from="1" to="#xmlsize#" index="a">
    

<b>Title:</b> #xmlfile.feed.entry.title.xmlText#<br>
<b>Format:</b> #xmlfile.feed.entry
.format.xmlText#<br>
<b>Author:</b> #xmlfile.feed.entry
.creator.xmlText#<br>
<b>Identifier1:</b> #xmlfile.feed.entry
.identifier.xmlText#<br>
<b>Identifier2:</b> #xmlfile.feed.entry
.identifier[2].xmlText#<br>

</cfoutput>
</cfloop>

This works reasonably well.  Here's the problem:  there is often a third identifier field (xmlfile.feed.entry.identifier[3].xmlText) -- but not always.

I'm trying to test for the existence of this field before outputting it.  I've tried the following:

<CFIF isdefined("xmlfile.feed.entry.identifier[3].xmlText")>
is defined

<CFELSE>

is not defined
</cfif>

That gives the typical error:

Parameter 1 of function IsDefined, which is now xmlfile.feed.entry.identifier[3].xmlText, must be a syntactically valid variable name.

I would like to use structkeyExists, but I can't figure out how to reference the third node (?) using the code:

<cfif structKeyExists(xmlfile.feed.entry,"identifier")> only works for xmlfile.feed.entry.identifier[1].xmlText

<cfif structKeyExists(xmlfile.feed.entry,"identifier[3]")> isn't valid.

So with strucktkeyexists, I cannot figure how to appropriately reference the variable name....

Any help?  Or better ideas to check for the existence of this variable?

    This topic has been closed for replies.
    Correct answer Owainnorth

    The node you're looking at is an array, therefore:

    <cfif arraylen(xmlfile.feed.entry.identifier) GT 2 >

    should do you. At present you're testing for the "xmltext" attribute rather than checking its parent node exists.

    HTH.

    Inspiring
    May 4, 2011

    You want to be checking the length of the identifier array (ie: are there three elements?)

    --

    Adam

    Owainnorth
    OwainnorthCorrect answer
    Inspiring
    May 4, 2011
    pkonshakAuthor
    Known Participant
    May 4, 2011

    So simple, and here I've been banging my head against a wall..

    Thanks for the lightning-fast responses!

    Peter

    Owainnorth
    Inspiring
    May 4, 2011

    Luckily, Adam and myself are clearly both trying to get out of doing any real work