I'm blanking on the best way to take an array and add it to an XML object.
I'm starting with an XML object that has empty nodes. Example XML:
<Request>
... other nodes ...
<Test></Test>
<Items>
<Item>
<Class></Class>
<Weight></Weight>
</Item>
</Items>
... other nodes ...
</Request>
I have parsed the XML above and can set data on the object just fine:
<cfset ParsedXML.Request.Test.XMLText = "Test">
Which results in this:
<Request>
... other nodes ...
<Test>Test</Test>
<Items>
<Item>
<Class></Class>
<Weight></Weight>
</Item>
</Items>
... other nodes ...
</Request>
So far so good. However, when I want to take a Coldfusion array and add it to XMLChildren, I'm running into a problem. So say I take an array of items:
<cfset ItemsArray = ArrayNew(1)>
<cfset ItemsArray[1] = {
"Class": 55,
"Weight": 100
}>
<cfset ItemsArray[2] = {
"Class": 55,
"Weight": 200
}>
And then I want to loop through that array to create new nodes inside 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>
I am getting this error:
The index of a child element is out of range. There are only 1 children under this node. Index 2 is out of the allowed range [1-1].
I've also tried XmlElemNew() but keep running into The right hand side of the assignment is not of type XML Node.
Is this what you are trying to accomplish? You need to treat any node you are trying to add to add (Item
, Class
, Weight
etc) to your xml as a 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#">