Earlier today, on the CF-Talk list, Brad Wood was asking about selecting any node from an XML document based on its text value (text child node). In my ColdFusion, XmlSearch, and XPath tutorial I did a bunch of stuff with "any node" examples and also with text-based examples, but I didn't do anything that combined the two. I didn't know if ColdFusion's XmlSearch() method would hiccup if you tried to use "//*" in conjunction with a text() predicate:
<!--- Build an XML document object. ---> <cfxml variable="xmlData"> <root> <a1>Meep</a1> <a2>Meep</a2> <a3> <b1>Dink</b1> <b2>Meep</b2> </a3> <a4>Blam</a4> </root> </cfxml> <!--- Get all nodes in the XML document that have the child text node, "Meep". We don't care where the node is or they are related... we only care about this inner text value. ---> <cfset arrNodes = XmlSearch( xmlData, "//*[ text() = 'Meep' ]" ) /> <!--- Dump out results. ---> <cfdump var="#arrNodes#" label="All Nodes By Text Value" />
I was pleased to see that this functions exactly like I hoped it would, giving us the following CFDump output:
Notice that it found the a1, a2, and b2 element nodes based purely on their nested text node. Good stuff.
Want to use code from this post? Check out the license.