Skip to main content
Participating Frequently
April 28, 2010
Question

Missing elements/attributes in XML

  • April 28, 2010
  • 2 replies
  • 1190 views

I'm using XmlParse to pull data out of xml files.  How do you handle cases where some of the xml contain elements/attributes that others do not?  There must be a graceful way to test for the existance of an element etc without using a try/catch, but I'm not sure what it is.  Any suggestions?

    This topic has been closed for replies.

    2 replies

    BKBK
    Community Expert
    Community Expert
    April 28, 2010

    It will certainly help to give an XML example, showing the data yo wish to pull out. by the way, xmlParse is for creating the XML document object, not for fetching data from the XML.

    April 28, 2010
    Participating Frequently
    April 29, 2010

    This is an example of what I'm doing:

    <cffile action="read" file="#currentXMLPath#" variable="xmlString" charset="utf-8" >
    <cfset mdXML = XmlParse(xmlString)>                                                   
    <cfset screens = XmlSearch(mdXML, "//*[local-name()='screens']" )>

    <cfset screenArray = #screens[1].screen#>                           
    <cfloop from="1" to="#ArrayLen(screenArray)#" index="i" step="1">
         <cfset objectInfo = #screenArray.objectInfo.XmlText#>

         ....

    </cfloop>

    The issue I'm having is that sometimes the objectInfo element (and others) won't be present in the xml, so I need to test for it's existance before trying to read it's value.  Am I going about this the wrong way?

    Inspiring
    April 29, 2010

    OK, so why don't you alter the xPath in your xmlSearch() to retrieve only the nodes you want, rather than get a whole bunch of nodes and then work out whether they're the ones you want or not?

    As BKBK suggested, seeing some sample XML indicating which nodes you want would help.

    --
    Adam