Last week, I talked about aggregating XML node text in a mixed-node ColdFusion XML document. In the comments of that post, Kirill pointed out that you could accomplish pretty much the same thing directly in the original xmlSearch() invocation using the XPath string() function. After trying this out for myself, I have to say that it is brilliant! It completely simplifies the entire process down to a single statement; and, if you throw in the normalize-space() function, it gets even better.
To see this in action, take a look at the following demo. In the code, we are going to take an XML branch and get the string representation of it and its child nodes.
<!--- Define our XML document. ---> <cfxml variable="data"> <data> <message> You are <em>wicked</em> sexy! </message> </data> </cfxml> <!--- Get the aggregate text value of the nodes. The string() method returns the string value of the node; the normalize-space() method strips leading/trailing spaces and condences multiples spaces into a single space. NOTE: Unlike most xmlSearch() calls, this one does not return a "Node" array - it returns a string value. ---> <cfset textValue = xmlSearch( data, "normalize-space( string( //message ) )" ) /> <!--- Output the text. ---> <cfoutput> Message: #htmlEditFormat( textValue )# </cfoutput>
As you can see, we are calling string() on the node-set, "//message". This returns the aggregate string representation of the node-set which we then trim and normalize. Doing this gives us the following page output:
Message: You are wicked sexy!
This is totally awesome! Notice that while most calls to xmlSearch() result in an array of nodes, this call results in a single string value. So, not only does this approach simplify the gathering of text, it simplifies the use of the resultant value.
A huge thanks to Kirill for pointing this out! I don't think that this task can get any easier at this point; it's about as simple and awesome as we can make it.
Want to use code from this post? Check out the license.