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

    @ThingsExpo Stories
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    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 ...
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
    Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
    DXWorldEXPO | CloudEXPO 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.
    The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
    DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO 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 over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    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...
    DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
    DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
    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...