Search code examples
coldfusioncoldfusion-10

Can't read the XML node elements in ColdFusion


I'm trying to read some values from the XML file which I created, but it gives me the following error:

coldfusion.runtime.UndefinedElementException: Element MYXML.UPLOAD is undefined in XMLDOC.

Here is my code

<cffile action="read" file="#expandPath("./config.xml")#" variable="configuration" />
<cfset xmldoc = XmlParse(configuration) />
<div class="row"><cfoutput>#xmldoc.myxml.upload-file.size#</cfoutput></div>

Here is my config.xml

<myxml>
 <upload-file>
  <size>15</size>
  <accepted-format>pdf</accepted-format>
 </upload-file>
</myxml> 

Can someone help me to figure out what is the error?

When I am printing the entire variable as <div class="row"><cfoutput>#xmldoc#</cfoutput></div> it is showing the values as

15 pdf


Solution

  • The problem is the hyphen - contained in the <upload-file> name within your XML. If you are in control of the XML contents the easiest fix will be to not use hyphens in your field names. If you cannot control the XML contents then you will need to do more to get around this issue.

    Ben Nadel has a pretty good blog article in the topic - Accessing XML Nodes Having Names That Contain Dashes In ColdFusion

    From that article:

    To get ColdFusion to see the dash as part of the node name, we have to "escape" it, for lack of a better term. To do so, we either have to use array notation and define the node name as a quoted string; or, we have to use xmlSearch() where we can deal directly with the underlying document object model.

    He goes on to give examples. As he states in that article, you can either quote the node name to access the data. Like...

    <div class="row">
        <cfoutput>#xmldoc.myxml["upload-file"].size#</cfoutput>
    </div>
    

    Or you can use the xmlSearch() function to parse the data for you. Note that this will return an array of the data. Like...

    <cfset xmlarray = xmlSearch(xmldoc,"/myxml/upload-file/")>
    
    <div class="row">
        <cfoutput>#xmlarray[1].size#</cfoutput>
    </div>
    

    Both of these examples will output 15.

    I created a gist for you to see these examples as well.