As I hack through our code base I just noticed this function. It converts an IDictionary<string, object> (Paramters – an instance variable) into an XML string.
This is nothing but curiosity on my part 🙂 .
So can it be written with a lot less code using C# 4.0?Rule: no external libs except the .Net Framework BCL.
To make it more of a challenge I’m not putting the input dictionary spec here, as you should be able to work it out from the code.
public string ConvertToXml() {
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version='1.0' encoding='utf-8'?><sc/>");
foreach (KeyValuePair<string, object> param in Parameters) {
XmlElement elm = doc.CreateElement("pr");
if (param.Value is int || param.Value is Int32 || param.Value is Int16 || param.Value is Int64) {
elm.SetAttribute("tp", "int");
} else if (param.Value is DateTime?){
elm.SetAttribute("tp", "datetime");
} else {
elm.SetAttribute("tp", "string");
}
elm.SetAttribute("nm", param.Key);
if (param.Value is DateTime?) {
DateTime? dateTime = param.Value as DateTime?;
elm.SetAttribute("vl", dateTime.Value.ToString("o"));
} else{
elm.SetAttribute("vl", param.Value.ToString());
}
doc.FirstChild.NextSibling.AppendChild(elm);
}
return doc.OuterXml;
}
Let me add some more thoughts.
To me :
- less is more but terse is bad
- more types are fine, but trivial types seem smelly
- reusability is good
Using dynamic and LINQ to XML:
ConvertToXml can be reduced to one statement (assuming omitting the XML declaration is acceptable).
Note that CreateElement casts param.Value to dynamic so that the correct overload from the following will be selected at runtime.
The overloads above ultimately call:
This code is reduces the number of statements (although not lines) found in the question. This approach builds on svick’s, but reduces the number of methods and dynamic calls required.