Check XML for the existence of a specific key

Viewed 51

In the following XML I want to see if there is element called "errors"

<cfxml variable="sXML">
<?xml version="1.0" encoding="UTF-8"?>
<createTransactionResponse>
   <messages>
      <message>
         <text>
            <XmlText>The transaction was unsuccessful.</XmlText>
         </text>
       </message>
     </messages>
   <transactionResponse>
     <errors>
       <error>
         <errorText>
           <XmlText>The credit card number is invalid.</XmlText>
         </errorText>
       </error>
     </errors>
   </transactionResponse>
 </createTransactionResponse>
</cfxml>

To see if node "errors" is present I used:

<cfif structKeyExists(sXML, "errors")>

But it comes back false (If the transaction was successful the XML doesn't have node "errors"). What am I doing wrong or is there a better way?

1 Answers

If you dump the xml stucture with <cfdump var="#sXML#">, it shows that "errors" is a child node, several levels down:

Dump of sXML nodes

You can reference it through the parent structures. Assuming the xml always contains the parent nodes "createTransactionResponse" and "transactionResponse", use:

<cfif structKeyExists(sXML.createTransactionResponse.transactionResponse, "errors")>
    Found
<cfelse>
    Not Found
</cfif>
Related