How to construct XML using String variables in Flex?


I discovered how to do this recently and wanted to share this…

Here’s the scenario – I have a String object which will be set at runtime. So it will contain different values at different times depending on the state of the application at that moment. And at the click of a button I want to construct an XML object in the following format –

value of String variable = Dr.House

then XML should be <name>Dr.House</name

and the contents within the <name> tag should whatever the string variable contains.

Normally XML objects in Flex/ActionScript are constructed this way – var xmlData:XML = new XML(); and then we do a xmlData.appendChild(). Another known way to create XML is when you know the XML contents at the time of coding and you create it this way –  var xmlData:XML = <list><name>Vatsala</name><name>Alfred Hitchcock</name></list>

But what if you are creating the XML object at runtime? Here’s how to do it –

var nameString:String = “Example”;  //this can be fed by a text input or whatever

var xmlData:XML = <name>{nameString}</name>;

This will result in the xml string <name>Example</name>.

Thats it.. Now you can use this XML object wherever you want to.

The key thing here is the use of  ‘{‘ and the ‘}’.  If you were to type var xmlData:XML = <name>nameString</name>, then the nameString will be taken at face value and the resulting xml string would be <name>nameString</name> and not <name>Example</name>.

The same thing can also be achieved this way-

var xmlData:XML = new XML(“<crfmodel>”+nameString+”</crfmodel>”);

Information about this is over at the Quick Starts page – and in the livedocs page

Advertisements

About vatsalad

Hi, I'm Vatsala
This entry was posted in flex, How To... and tagged , , , , . Bookmark the permalink.