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
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
    The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    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, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – 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 results. Among the proven benefits,...
    @DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
    SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
    SYS-CON Events announced today that Cedexis 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. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
    SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
    SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
    SYS-CON Events announced today that Opsani 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. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
    SYS-CON Events announced today that Nirmata 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. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
    SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...