【问题标题】:How do I add an array to an XML object in Coldfusion?如何在 Coldfusion 中将数组添加到 XML 对象?
【发布时间】:2020-06-03 18:33:42
【问题描述】:

我正在讨论获取数组并将其添加到 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】:

    这是您想要完成的任务吗?您需要将尝试添加的任何节点(ItemClassWeight 等)作为XmlChildren 添加到您的 xml。

    <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

    【讨论】:

    • 这正是我所需要的。我应该详细说明我的 XMLElemNew() 尝试,但我现在可以看到我没有做的是首先添加 Item 节点,然后添加子节点(Class 和 Weight)。感谢您抽出宝贵时间回答,这是一个巨大的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-02-22
    • 2014-07-16
    • 2021-11-06
    相关资源
    最近更新 更多