I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code.
function init() {
var myOptions = { : 'Select home value', // <== THERE'S THE NON EXISTANT KEY
100000 : '$90,001 - $100,000',
1000000 : '$950,001 - $1,000,000',
1000001 : 'Over $1,000,000', // <== HERE'S THE COMMA I'M CURIOUS ABOUT
};
Here is the code that is being generated
protected string DoTransform()
{
var sb = new StringBuilder("var myOptions = {");
foreach (var option in
XDocument.Load(MapPath("~/App_Data/Data.xml"))
.XPathSelectElements("./data/options[@question='ApproximatePropertyValue']/option"))
{
sb.AppendFormat("{0} : '{1}',\n", option.Attribute("value").Value, option.Value);
}
sb.AppendLine("};");
return sb.ToString();
}
ANSWER: Here is the updated code that handles the empty key (by skipping the first element) and trailing comma (by reorganizing logic for TrimEnd to remove it).
protected string DoTransform()
{
var sb = new StringBuilder();
foreach (var option in
XDocument.Load(MapPath("~/App_Data/Data.xml"))
.XPathSelectElements("./data/options[@question='ApproximatePropertyValue']/option")
.Skip(1))
{
sb.AppendFormat("{0}:'{1}',", option.Attribute("value").Value, option.Value);
}
return"var myOptions = {\n" + sb.ToString().TrimEnd(',') + "};";
}