• home
  • forum
  • my
  • kt
  • download
  • Generating XML with ColdFusion - A Rough Guide

    Author: 2008-08-05 06:38:22 From:

    For this short tutorial I shall not be reverting to my usual tutorial structure.  For anyone who has experience in ColdFusion and HTML (which should be everyone who is reading this document) the following should be a relatively easy to follow.

    In order to pass any data to an XML file we firstly need to generate a data set.  How this is done is up to the developer and is determined by the project although for this example I will use a query.

    <CFQUERY name="CreateXML" datasource="myDataSource">
     SELECT productid, ordercode, productname, baseprice
     FROM products
    </CFQUERY>


    As you can see, the above is a very simple query on a single database table.

    Now lets look at writing this to an XML file with ColdFusion.

    We need to first give our XML document a valid XML header.  This is done as follows.  Note the inclusion of our first XML root and how I have escaped the " by using "".

    <CFSET xmldoc = "<?xml version=""1.0""?>
    <products>
    ">

    Now we have the top of our document we need to decide on our XML structure and loop over the query results in order to populate the variable.  The following section of code concatenates onto the previous variable value for each iteration of the loop.  This in turn, forms the XML document.  Notice how I also use two ColdFusion functions, Trim() and XMLFormat().  These are used to ensure that the values returned by the query are safe for use in XML and contain no extraneous spaces.  The pound or hash # sign is used to identify variables within the CFSET string and is necessary in this case.

    <CFLOOP query="CreateXML">
    <CFSET xmldoc = xmldoc & "
      <productid>#Trim(XMLFormat(productid))#</productid>
      <ordercode>#Trim(XMLFormat(ordercode))#</ordercode>
      <productname>#Trim(XMLFormat(productname))#</productname>
      <baseprice>#Trim(XMLFormat(baseprice))#</baseprice>
    ">
    </CFLOOP>

    Before we can write our variable value to a file however, we need to close the root tag.  This is done as follows:

    <CFSET xmldoc = xmldoc & "</products>">

    Now we have a complete variable containing an entire XML file.  Let's write it to a file.

    <CFSET filename= ExpandPath("./") & "products.xml">
    <CFFILE action="write" file="#filename#" output="#xmldoc#">

    Just so we are able to check our code, we can for example, use CFLOCATION to redirect us to our new XML page.

    Congratulations, you've just generated your first dynamic XML using ColdFusion.

    discuss this topic to forum

    relation tutorial

    No relevant information

    New

    Hot