Welcome!

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">
    <Employees>
    <Employee ID="XXX">
    ...
    Child Elements
    ...
    </Employee>
    </Employee>
    </CFXML>
    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">
    <Employee>
    ...
    </Employee>
    </CFOutput>
    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#">
    <FirstName>#XMLFormat(qEmps.FirstName)
    #</FirstName>
    </Employee>
    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"
    file="#ExpandPath('.')#\employees.xml"
    output="#toString(xmlDoc)#">
    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[
    ArrayLen(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=
    qEmps.FirstName>
    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.

    Limitations
    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.)

    Conclusion
    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

    @ThingsExpo Stories
    In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
    With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
    Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
    SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
    WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a mu...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
    SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
    SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
    SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
    SYS-CON Events announced today that WineSOFT will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
    SYS-CON Events announced today that Akvelon will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
    SYS-CON Events announced today that TechTarget has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TechTarget storage websites are the best online information resource for news, tips and expert advice for the storage, backup and disaster recovery markets.
    Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
    SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we've...
    DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, will present a step-by-step plan to develop your technology implementation strategy. He will discuss the evaluation of communication standards and IoT messaging protocols, dat...
    SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
    Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
    SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).