如何在Coldfusion中将数组添加到XML对象?

问题描述 投票:3回答:1

我正在研究采用数组并将其添加到XML对象的最佳方法。

我从一个具有空节点的XML对象开始。 XML示例:

<Request>
    ... other nodes ...
    <Test></Test>
    <Items>
      <Item>
        <Class></Class>
        <Weight></Weight>
      </Item>
    </Items>
    ... other nodes ...
</Request>

我已经解析了上面的XML,可以在对象上设置数据了:

<cfset ParsedXML.Request.Test.XMLText = "Test">

导致的结果:

<Request>
    ... other nodes ...
    <Test>Test</Test>
    <Items>
      <Item>
        <Class></Class>
        <Weight></Weight>
      </Item>
    </Items>
    ... other nodes ...
</Request>

到目前为止很好。但是,当我要使用Coldfusion数组并将其添加到XMLChildren时,遇到了问题。所以说我带了一些物品:

<cfset ItemsArray = ArrayNew(1)>
<cfset ItemsArray[1] = {
    "Class": 55,
    "Weight": 100
}>
<cfset ItemsArray[2] = {
    "Class": 55,
    "Weight": 200
}>

然后,我想遍历该数组以在ResponseNodes.Request.Items.XMLChildren中创建新节点:

<cfset ItemRow = 1>
<cfloop array="#ItemsArray#" index="i">
    <cfset ParsedXML.Request.Items.Item[ItemRow].Class.XMLText = i.Class>
    <cfset ParsedXML.Request.Items.Item[ItemRow].Weight.XMLText = i.Weight>
    <cfset ItemRow = ItemRow + 1>
</cfloop>

我收到此错误:

子元素的索引超出范围。 该节点下只有1个孩子。 索引2超出允许范围[1-1]。

我也尝试过XmlElemNew(),但继续遇到The right hand side of the assignment is not of type XML Node.

xml coldfusion cfml coldfusion-11
1个回答
3
投票

这是您要实现的目标吗?您需要将要添加的任何节点(ItemClassWeight等)都视为XmlChildren

<cfset ItemsArray = [
  {"Class": 55, "Weight": 100},
  {"Class": 55, "Weight": 200},
  {"Class": 55, "Weight": 300}
]>

<cfxml variable="ParsedXML">
  <cfoutput>
  <Request>
      <Test></Test>
      <Items>
      </Items>
  </Request>
  </cfoutput>
</cfxml>
<cfset ParsedXML.Request.Test.XMLText = "Test">
<cfset ItemRow = 1>
<cfloop array="#ItemsArray#" index="i">
  <cfset ParsedXML.Request.Items.XmlChildren[ItemRow] = XmlElemNew(ParsedXML,"Item")> 
  <cfset ParsedXML.Request.Items.XmlChildren[ItemRow].XmlChildren[1] = XmlElemNew(ParsedXML,"Class")> 
  <cfset ParsedXML.Request.Items.XmlChildren[ItemRow].XmlChildren[2] = XmlElemNew(ParsedXML,"Weight")> 
  <cfset ParsedXML.Request.Items.XmlChildren[ItemRow].XmlChildren[1].XMLText = i.Class>
  <cfset ParsedXML.Request.Items.XmlChildren[ItemRow].XmlChildren[2].XMLText = i.Weight>
  <cfset ItemRow += 1>
</cfloop>
<cfdump var="#ParsedXML#">

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.