Skip to main content
February 11, 2010
Question

xml

  • February 11, 2010
  • 1 reply
  • 766 views

How could i check to see if a specific xml element exists? I have the following xml document:

<employee>

     <id>101</id>

     <name>Janice Henry</name>

     <zip>33021</zip>

</employee>

<employee>

     <id>102</id>

     <name>Julian Andrews</name>

</employee>

And i want to be able to check to see if the <zip> element exists.

    This topic has been closed for replies.

    1 reply

    BKBK
    Community Expert
    Community Expert
    February 11, 2010

    There are two issues. First, whether or not the zip element exists for an employee. Secondly, whether or not there is a value for the element.

    For a start, the XML must have a root element. I have called it employees.

    <cfxml variable="xmlDoc">
    <employees>
        <employee>
             <id>101</id>
             <name>Janice Henry</name>
             <zip>33021</zip>
        </employee>
        <employee>
             <id>102</id>
             <name>Julian Andrews</name>
        </employee>
    </employees>
    </cfxml>

    Each employee element is a child of the xmlRoot, employees. The employee elements are therefore xmlDoc.xmlRoot.xmlChildren[1] and xmlDoc.xmlRoot.xmlChildren[2]. The following loop runs through the employee elements, and displays each employee's zip, if it exists

    <cfloop from="1" to="#arrayLen(xmlDoc.xmlRoot.xmlChildren)#" index="idx">
        <cfif structkeyexists(xmlDoc.xmlRoot.xmlChildren[idx], "zip")>
            Element index: <cfoutput>#idx#</cfoutput><br>
            zip: <cfoutput>#xmlDoc.xmlRoot.xmlChildren[idx]["zip"].xmlText#</cfoutput><br>
        </cfif>
    </cfloop>

    February 11, 2010

    Wow, that was exactly what i was looking for, thank you very much.