无法读取 ColdFusion 中的 XML 个节点元素

Can't read the XML node elements in ColdFusion

我正在尝试从我创建的 XML 文件中读取一些值,但出现以下错误:

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

这是我的代码

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

这是我的 config.xml

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

谁能帮我弄清楚错误是什么?

当我将整个变量打印为 <div class="row"><cfoutput>#xmldoc#</cfoutput></div> 时,它显示的值是

15pdf

问题是 XML 中 <upload-file> 名称中包含的连字符 -。如果您可以控制 XML 内容,最简单的解决方法是不要在您的字段名称中使用连字符。如果您无法控制 XML 内容,那么您将需要采取更多措施来解决此问题。

Ben Nadel 在主题中有一篇相当不错的博客文章 - Accessing XML Nodes Having Names That Contain Dashes In ColdFusion

来自那篇文章:

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.

他继续举例。正如他在那篇文章中所说,您可以引用节点名称来访问数据。喜欢...

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

或者您可以使用xmlSearch()函数为您解析数据。请注意,这将 return 一个数据数组。喜欢...

<cfset xmlarray = xmlSearch(xmldoc,"/myxml/upload-file/")>

<div class="row">
    <cfoutput>#xmlarray[1].size#</cfoutput>
</div>

这两个例子都会输出 15.

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