Checking for child node in xml document with coldfusion

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.

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.

      <title>Rock Star</title>

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 myXMLDoc = XMLParse("")>
<cfset xmlResult = XMLSearch(myXMLDoc, "/employees")>

<cfloop from="1" to="#arrayLen(XMLSearch(xmlResult, '/employees'))#" index="i">
<cfif xmlChildPos(xmlResult[i].employee,"children", 1) GT 0>

Thats it. Enjoy!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.