You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

ColdFusion MX and XML: Creating XML Part 2

ColdFusion MX and XML: Creating XML Part 2

I'll plead guilty to having tortured more than my share of bytes into completely unnatural configurations.

In the BX years (Before XML), if you had to share data with your business partners you might have represented the data in comma-delimited text files. If the data was too complex to fit one record to a line, you might have created a proprietary design to hold the information.

Today you'd probably consider XML. Its consistency makes it possible to create and parse text-based data files with standardized programming tools. When deciding how to transfer your data to XML you'd have a choice of programming approaches. Some would be hard, others easier, but until now none would have been native ColdFusion.

That's changed with the release of ColdFusion MX. This is the second of three articles describing the new XML development tools in CFMX. In the first article (CFDJ, Vol. 4, issue 6) I described methods for parsing, extracting, and searching for data from XML. This month I'll describe the new tools for turning your data into XML.

Toto, I Don't Think We're in WDDX Anymore
When I speak of XML, I'm not just talking about Web Distributed Data Exchange (WDDX), which has been supported in ColdFusion since version 4. While WDDX is a wonderful XML language, it hasn't been adopted widely beyond the world of Macromedia. The rest of the computing world uses other variants of XML, and there are too many different flavors to count. You need to be able to publish XML in any format, not just WDDX. That's what these tools provide.

Imagine that I have a database table containing employee information that I want to move to XML. In this example I'll use the employees table from the CFSnippets database that's installed with CFMX.

CFMX offers two methods for creating and publishing an XML document:

  • The "Text" method uses the new <CFXML> tag and allows you to model the XML tree as text, much as you use <CFOutput> to model HTML output.

  • The "Object" method uses CFMX's new XML functions to build an object model.

    The Text method is considerably easier to use, but I'll show both approaches and you can decide for yourself.

    Modeling XML as Text
    The Text method builds the XML structure as text, then converts it to an XML document object variable. First, create a model of the XML structure inside a pair of <CFXML> tags. Use placeholders to indicate where the variable data will go:

    <CFXML variable="xmlDoc">
    <Employee ID="XXX">
    Child Elements
    The <CFXML> tag creates a new XML document object variable named xmlDoc. As I described in the last article, you can view the structure of the resulting XML document object with the <CFDump> command:

    <CFDump var="#xmlDoc#">

    See Figure 1 for the dumped structure of the XML document before being populated with real data.

    Adding Your Data
    Assuming your content is in a database, add a <CFQuery> before the call to <CFXML>. To add variable content to the XML document, wrap the employee element with a <CFOutput> tag pair that loops over the query contents. This is just like looping over a query to create multiple list items or table rows in HTML:

    <CFOutput query="qEmps">
    To place the data where you want it, replace the placeholders with the data from the query. If there might be any reserved characters in a value, such as ampersands (&), quotes ("), or tag symbols ("<" or ">"), wrap the value with the XML-Format() function. This replaces any such characters with their equivalent entities and ensures that your XML is well formed:

    <Employee ID="#qEmps.Emp_ID#">
    Notice that the element tags are wrapped around the value without any additional white space (spaces, tabs, line feeds). Adding such space for readability is fine when creating HTML, since the Web browser usually normalizes the resulting output, removing extra spaces. In XML you'd be changing the data.

    Your XML document object has been created. Once again, you can view the structure of the document with <CFDump>. See Listing 1 for the complete code, and Listing 2 for the contents of the XML file it creates.

    The toString() Function
    Right now your XML document is a structured object that you can read programmatically using the techniques described in last month's article. To share the data, you now need to convert the document to text. For this, wrap the XML document object variable in the toString() function. For instance, to publish the XML document to a text file, use this code:

    <CFFile action="WRITE"
    The toString() function adds an XML declaration at the beginning of the output and always sets the declaration's "encoding" attribute to UTF-8.

    Modeling XML as Objects
    The Object method of creating XML files uses two new XML functions:

    • XMLNew(): Creates a new XML document
    • XMLElemNew(): Creates a new XML element
    Start with XMLNew(). This function returns an instance of an empty XML document:

    <CFSet xmlDoc=XMLNew()>

    The document initially isn't well formed - that is, it doesn't contain any elements. So next you'll create a new element as a child of the document. XMLElemNew() takes two arguments. The first is the XML document object to which you're adding the element. The second is the name of the new element.

    The document has a built-in child object named xmlRoot. By assigning a new element to the xmlRoot, you're creating the document's root element:

    <CFSet xmlDoc.xmlRoot=
    xmlElemNew(xmlDoc, "Employees")>
    <CFSet root=xmlDoc.XMLRoot>
    Now, loop through the query just as before, but this time create elements to represent each employee. Each element contains a built-in array named XMLChildren, and each item of the array is a child element. Adding a new employee element to the root looks like this:

    <CFSet ArrayAppend( root.xmlChildren,
    xmlElemNew(xmlDoc, "Employee") )>
    As the XML hierarchy gets deeper, the syntax for referring to any particular element can get unwieldy. So now create a reference variable that points to the element you just created:

    <CFSet emp=root.xmlChildren[
    Each employee has an ID that I'd like to store as an XML attribute. Each element has a built-in structure called XMLAttributes. When you assign an item to the structure, you're adding an attribute to the element:

    <CFSet emp.xmlAttributes.ID = qEmps.Emp_ID>

    Each employee has a set of values that I want to store as child elements with text values between the tags. Once again I'll use XMLElemNew() to create the element, then set the new element's built-in XMLText property to the value from the query. I don't have to use the XMLFormat() function to wrap the data as the Object method replaces any reserved characters for me:

    <CFSet ArrayAppend( emp.xmlChildren,
    xmlElemNew(xmlDoc, "FirstName"))>
    <CFSet emp.FirstName.xmlText=
    Repeat this step for each of the child elements you want to add and populate with data. When you run the code you'll have created an XML document object containing your data.

    This time, instead of saving to disk, I'll share the XML over the HTTP connection. Before outputting to the browser, I'll use <CFContent> to set the content type to XML. This lets any users of the data know that they're getting the right type of information:

    <CFContent type="text/xml">

    The code for the Object method is in Listing 3.

    White-Space Issues
    You may notice that the <CFXML> version of the output has a little too much white space between employee elements. This is okay as an XML parser doesn't make any distinction between a little bit of white space and a lot of white space.

    The Object version, though, comes out in a single line and is difficult for the human eye to read:

    <Employees><Employee ID="1"><FirstName>...

    I fix this with a call to a user-defined function I wrote named XMLIndent() (stored in a file named xml-Utilities.cfm). See Listing 4 for its contents.

    XMLIndent() passes the XML document through an XSLT (Extensible Stylesheet Language Transformation) template that returns the XML document as is, but adds hard returns to make it more readable. XMLIndent() takes the XML document as an argument and returns a text representation of the indented result:

    <CFInclude template="xmlUtilities.cfm">
    <CFSet xmlText=xmlIndent(xmlDoc)>
    I'll discuss this UDF more thoroughly in the next article, which describes what you can do with ColdFusion and XSLT.

    Both methods of creating XML files have these limitations:

  • UTF-8 encoding only: While the toString() function has an "encoding" attribute, it doesn't work for the XML document object. And while CFFile now has a "charset" attribute to output in other encoding formats, it doesn't affect the resulting XML declaration's encoding attribute. You can easily end up with a file in UTF-16 format, but an XML declaration that claims the file is in UTF-8.

  • No Document Type Declarations: There is no built-in method for assigning a Document Type Definition (DTD) to the XML output. Adding the DTD to the XML text in <CFXML> doesn't throw an error, but it's also ignored.

    I'll describe workarounds for both of these problems in the next article. (If you need either of them right away, e-mail me.)

    I've described two methods of creating XML files with ColdFusion MX. The Text method uses <CFXML> and will seem most intuitive to experienced ColdFusion developers as it allows you to create XML with the same simple methods we use to create HTML dynamically. The Object method gives you greater control over the structure of your XML document at the expense of greater coding complexity. Either method allows you to export your data to any XML language with relative ease.

    *  *  *

    In the last article of this series I'll describe the use of XSLT and the new XMLTransform() function, including how to use XSLT to move your data from WDDX to other flavors of XML and back again.

  • Comments (1) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    Most Recent Comments
    kuzma 07/24/08 05:53:25 AM EDT

    Useless sheet. Bunch of text and 10 lines of code.
    i do not need novels , i need example all other things I'll find myself

    IoT & Smart Cities Stories
    Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
    All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
    The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
    CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
    Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
    The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
    SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...