首页 > 解决方案 > 检查 XML 是否存在特定键

问题描述

在以下 XML 中,我想查看是否存在名为“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>

要查看是否存在节点“错误”,我使用了:

<cfif structKeyExists(sXML, "errors")>

但它又回来了false(如果事务成功,则 XML 没有节点“错误”)。我做错了什么还是有更好的方法?

标签: xmlcoldfusion

解决方案


如果您使用 转储 xml 结构<cfdump var="#sXML#">,则表明“错误”是一个子节点,向下几个级别:

sXML 节点的转储

您可以通过父结构引用它。假设 xml 总是包含父节点“createTransactionResponse”和“transactionResponse”,使用:

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

推荐阅读