Suppose I have a XML file: <?xml version="1.0"?> <person> <name> <firstname>John</firstname> <lastname>Barrett</lastname> </name> </person> Now I want to add another name to this XML file. How can I create a CF form (I am fine with creating the form) and post the content of that form (user input) to update the xml file?
A new record can be inserted by first reading the xml file to a varaible using cffile. The new record may then be inserted using ArrayAppend and XmlElemNew functions before finally writing it to file using cffile again.
<!--- Collect the values to be inserted nto the new record using form --->
<cfset newBrandID1 = 111> <cfset newBrandName1 = "name1"> <cfset newBrandImage1 = "image1"> <cfset newBrandID2 = 222> <cfset newBrandName2 = "name2"> <cfset newBrandImage2 = "image2">
<cffile action="read" file="#Expanded file path\xml filename#" variable="xmlFile"> <cfset myXml = XmlParse(xmlFile)> <cfset myXmlLength = ArrayLen(myXml.brands.xmlChildren)>
<cfset myXml.brands.XmlChildren[#myXmlLength# + 1] = XmlElemNew(myXml,"brand")> <cfset myXml.brands.XmlChildren[#myXmlLength# + 1].XmlChildren[1] = XmlElemNew(myXml,"brandid")> <cfset myXml.brands.XmlChildren[#myXmlLength# + 1].XmlChildren[2] = XmlElemNew(myXml,"brandname")> <cfset myXml.brands.XmlChildren[#myXmlLength# + 1].XmlChildren[3] = XmlElemNew(myXml,"brandimage")>
<cfset myXml.brands.XmlChildren[#myXmlLength# + 2] = myXml.brands.XmlChildren[#myXmlLength#]>
<cfset myXml.brands.XmlChildren[#myXmlLength# + 1].brandid.xmltext = #newBrandID1#> <cfset myXml.brands.XmlChildren[#myXmlLength# + 1].brandname.xmltext = #newBrandName1#> <cfset myXml.brands.XmlChildren[#myXmlLength# + 1].brandimage.xmltext = #newBrandImage1#> <cfset myXml.brands.XmlChildren[#myXmlLength# + 2].brandid.xmltext = #newBrandID2#> <cfset myXml.brands.XmlChildren[#myXmlLength# + 2].brandname.xmltext = #newBrandName2#> <cfset myXml.brands.XmlChildren[#myXmlLength# + 2].brandimage.xmltext = #newBrandImage2#>
<cffile action="write" file="#Expanded file path\xml filename#l" output="#tostring(myXml)#">
+