Checking for child node in xml document with coldfusion
Problem:
The xml document I was trying to invoke would sometimes return child nodes, and sometimes not. Since I would reference the values of the child nodes in my result set, I needed to first check to see if they existed.
isDefined doesn't work with Xml documents, and I didn't want to convert it to another object type just for that. I could have tried to reference the child node with a try/catch around it and if it broke, then I knew it didn't exist. Thats a bit messy and more of a hack than I'm comfortable with.
Solution:
After a bit of searching, I remembered "XmlChildPos". It returns the location of the child node, and if no child is found, returns a "-1"! Mission accomplished.
XmlChildPos(elem, childName, N)
Here's an example xml document where one person has children, and another does not.
<employee>
<name>Bob</name>
<title>Rock Star</title>
<children>3</children>
<employee>
<employee>
<name>Tom</name>
<title>Accountant</title>
<employee>
</employees>
Now, I don't know if this is properly formatted xml or what, but its being sent this way from a very, very big company who aren't going to change it.
So, I bring in the xml and store it in a variable called "xmlResult" that starts at the "employees" level.
I need to see if children exists for employee "Tom" and display the amount if it does.
<cfset xmlResult = XMLSearch(myXMLDoc, "/employees")>
<cfloop from="1" to="#arrayLen(XMLSearch(xmlResult, '/employees'))#" index="i">
<cfif xmlChildPos(xmlResult[i].employee,"children", 1) GT 0>
#xmlResult[i].employee.children#
</cfif>
</cfloop>
Thats it. Enjoy!


There are no comments for this entry.
[Add Comment]