ColdFusion XML Object Will Auto-Convert To String Often, But Not Always
Posted July 2, 2007 at 5:08 PM
I was just playing around with some ColdFusion XML RPC functionality when I accidentally treated the XML document object as a string, not as a complex value. Of course, the reason I didn't notice it at first is because ColdFusion will automatically convert the XML Document Object to an XML string when it is required for string manipulation. So for instance, the following code:
Launch code in new window » Download code as text file »
- <!--- Create an XML value. --->
- <cfxml variable="xmlGirl">
-
- <?xml version="1.0" encoding="UTF-8"?>
- <name>
- Julia Stiles
- </name>
-
- </cfxml>
-
- <!--- Output XML as string. --->
- #xmlGirl#
... simply outputs the XML string:
Launch code in new window » Download code as text file »
- <?xml version="1.0" encoding="UTF-8"?>
- <name>
- Julia Stiles
- </name>
Likewise, when I try to run:
Launch code in new window » Download code as text file »
- <!--- Get trimmed XML string. --->
- <cfset xmlData = Trim( xmlGirl ) />
ColdFusion does not error. It just returns the trimmed XML string representation of the XML document object. This is kind of cool, but I am not sure how I feel about it. I generally don't like implicit data conversion as it can lead to problems when you expect one thing and get another. For instance, if you pass the ColdFusion XML document object to the function, ToBase64():
Launch code in new window » Download code as text file »
- <!--- Get the Base64 encoding of the XML. --->
- #ToBase64( xmlGirl )#
... ColdFusion throws the following error:
Could not convert the value of type class coldfusion.xml.XmlNodeList to binary.
The problem here is that ToBase64() can take either a string OR a binary object. I guess it first tries to convert the XML document object to binary before it tries to convert it to a string. So, where as everything was copasetic as an argument to one function, it bombs out as an argument to another function.
So, while I didn't realize that ColdFusion automatically converts XML document objects to strings when necessary, I would still suggest actually calling the ToString() method (and passing in the XML object) when you need the string representation:
Launch code in new window » Download code as text file »
- <!--- Get string value for XML document. --->
- #ToString( xmlGirl )#
That way, there are no surprises.
Download Code Snippet ZIP File
Post Comment | Ask Ben | Permalink | Other Searches | Print Page
Newer Post
Lenny And Bo, ColdFusion Programmers (Vol. 23)
Older Post
jQuery v1.1.3 Now 800% Faster (At The Same Size File)!
Reader Comments
That CF8 banner if f'ing hilarious!
Oh and good post on the xml...
@Russ,
Thanks on both counts. I got bored of serving up Google AdSense ads all the time, so I started making a few banner ads just for fun :) Gives me something to do when I don't feel in the coding mood.




