How to use variables in your XML declarations

How to use variables for parts of your XML instead of static XML declarations.

You can easily create XML through string manipulation like the following:

var myXML = new XML("this is the link");

but this is slow and requires that the XML be parsed. There will be situations sometimes where you will have a set number of nodes but those nodes will contain different data or be named differently. The below code shows you the most efficient way of doing this.

here is some static hardcoded XML:

here is an XML declaration using variables to create the XML:

This is called embedding variables inside of your XML declaration. I use this for a few different reasons. For example if I have a function with parameters and every time that function is called those parameters variables are used to populate an XML form that is created and then is removed from memory every time the function is called. As we all know if you have an intensive loop with hundreds of thousands of iterations optimization can be important this is one of those situations that works faster than the converting of a string to XML. Sometimes it is just more clean and readable to write code this way instead of creating the XML and then having a bunch of hard to read E4X afterwords in order to insert the variables into your XML. Also it can be faster to program rather than using XML manipulation. if every time the XML is going to be created it will be populated with variables in a different fashion why not just embed the variables into the declaration. These are just a few of the advantages of using variables in your XML declarations.

Feel free to leave comments if you like what you saw or if you were looking for something else and I could update this article with that something else.

comments powered by Disqus