当我浏览我们的代码库时,我才注意到这个函数。它将IDictionary<string, object>
(参数 - 实例变量)转换为XML字符串。
这只不过是我的好奇心:-)。
使用C#4.0可以用更少的代码编写吗?规则:除了.Net Framework BCL之外没有外部库。
为了让它更具挑战性,我不会在这里输入输入字典规范,因为你应该可以从代码中解决它。
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;
}
让我再添加一些想法。
对我来说:
答案 0 :(得分:8)
使用LINQ to XML可以使编写起来非常简单。如果您可以选择,请将其优先于标准XML库。
我认为这应该是等同的:
public static string ToXmlString(this IDictionary<string, object> dict)
{
var doc = new XDocument(new XElement("sc", dict.Select(ToXElement)));
using (var writer = new Utf8StringWriter())
{
doc.Save(writer); // "hack" to force include the declaration
return writer.ToString();
}
}
class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
static XElement ToXElement(KeyValuePair<string, object> kvp)
{
var value = kvp.Value ?? String.Empty;
string typeString;
string valueString;
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
typeString = "int";
valueString = value.ToString();
break;
case TypeCode.DateTime:
typeString = "datetime";
valueString = ((DateTime)value).ToString("o");
break;
default:
typeString = "string";
valueString = value.ToString();
break;
}
return new XElement("pr",
new XAttribute("tp", typeString),
new XAttribute("nm", kvp.Key),
new XAttribute("vl", valueString));
}
请注意,检查值是否为DateTime?
类型是没有意义的。我不确定在字典中存储null
值有什么价值,但如果可能的话,你会因为制作object
类型的值而失去那种类型信息。
此外,如果DateTime?
值不是null
,则值本身将被加框,而不是Nullable<DateTime>
结构本身。因此实际类型为DateTime
,这就是此代码有效的原因。
答案 1 :(得分:6)
使用动态和LINQ to XML:
ConvertToXml可以简化为一个语句(假设可以省略XML声明)。
public string ConvertToXml()
{
return new XElement("sc",
Parameters.Select(param => CreateElement(param.Key, (dynamic)param.Value))
).ToString(SaveOptions.DisableFormatting);
}
请注意,CreateElement会将param.Value强制转换为动态,以便在运行时选择以下正确的重载。
XElement CreateElement(string key, object value)
{
return CreateElement("string", key, value.ToString());
}
XElement CreateElement(string key, long value)
{
return CreateElement("int", key, value.ToString());
}
XElement CreateElement(string key, DateTime value)
{
return CreateElement("datetime", key, value.ToString("o"));
}
上面的重载最终会调用:
XElement CreateElement(string typename, string key, string value)
{
return new XElement("pr",
new XAttribute("tp", typename),
new XAttribute("nm", key),
new XAttribute("vl", value)
);
}
此代码减少了问题中的语句数量(尽管不是行)。这种方法建立在svick's之上,但减少了所需的方法和动态调用的数量。
答案 2 :(得分:5)
使用.net 4.0功能,例如Tuple
和dynamic
关键字。我的测试用例产生了原始问题的精确输出。
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Xml.Linq;
public string ConvertToXml()
{
//Create XDocument to specification with linq-to-xml
var doc = new XDocument(
new XElement("sc",
from param in Parameters
//Uses dynamic invocation to use overload resolution at runtime
let attributeVals = AttributeValues((dynamic)param.Value)
select new XElement("pr",
new XAttribute("tp", attributeVals.Item1),
new XAttribute("nm", param.Key),
new XAttribute("vl", attributeVals.Item2)
)
)
);
//Write to string
using (var writer = new Utf8StringWriter())
{
doc.Save(writer, SaveOptions.DisableFormatting);//Don't add whitespace
return writer.ToString();
}
}
//C# overloading will choose `long` as the best pick for `short` and `int` types too
static Tuple<string, string> AttributeValues(long value)
{
return Tuple.Create("int", value.ToString());
}
//Overload for DateTime
static Tuple<string, string> AttributeValues(DateTime value)
{
return Tuple.Create("datetime", value.ToString("o"));
}
//Overload catch all
static Tuple<string, string> AttributeValues(object value)
{
return Tuple.Create("string", value.ToString());
}
// Using John Skeet's Utf8StringWriter trick
// http://stackoverflow.com/questions/3871738/force-xdocument-to-write-to-string-with-utf-8-encoding/3871822#3871822
class Utf8StringWriter : System.IO.StringWriter
{
public override System.Text.Encoding Encoding { get { return System.Text.Encoding.UTF8; } }
}
任选地: 将let语句改为:
let attributeVals = (Tuple<string,string>)AttributeValues((dynamic)param.Value)
这会将动态调用限制在该行。但是由于没有其他事情发生,我认为不想添加额外的演员会更清洁。
答案 3 :(得分:5)
public string ConvertToXml()
{
var doc = new XDocument(
new XElement("sd",
Parameters.Select(param =>
new XElement("pr",
new XAttribute("tp", GetTypeName((dynamic)param.Value)),
new XAttribute("nm", param.Key),
new XAttribute("vl", GetValue((dynamic)param.Value))
)
)
)
);
return doc.ToString();
}
此代码假定您将重载方法GetTypeName()
和GetValue()
实现为:
static string GetTypeName(long value)
{
return "int";
}
static string GetTypeName(DateTime? value)
{
return "datetime";
}
static string GetTypeName(object value)
{
return "string";
}
static string GetValue(DateTime? value)
{
return value.Value.ToString("o");
}
static string GetValue(object value)
{
return value.ToString();
}
这使用了这样一个事实:当使用dynamic
时,将在运行时选择正确的重载。
int
和short
不需要重载,因为它们可以转换为long
(这种转换被认为比转换为object
更好)。但这也意味着ushort
和byte
等类型将获得tp
int
。{/ p>
此外,返回的字符串不包含XML声明,但无论如何声明UTF-16编码的字符串是UTF-8编码都没有意义。 (如果您希望稍后将其保存在UTF-8编码文件中,则返回并保存XDocument
会更好,并且会编写正确的XML声明。)
我认为这是一个很好的解决方案,因为它很好地将关注点分成不同的方法(你甚至可以将GetTypeName()
和GetValue()
重载到不同的类中。)
答案 4 :(得分:2)
考虑到新的要求,重新接受了批准。
方法本身:
public string ConvertToXml(
IDictionary<string, object> rawData,
Dictionary<TypeCode, Func<object, Tuple<string, string>>> transformationFactoryProvider)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version='1.0' encoding='utf-8'?><sc/>");
if (rawData != null)
{
Func<object, Tuple<string, string>> defaultFactory =
(raw) => Tuple.Create("string", raw.ToString());
foreach (KeyValuePair<string, object> item in rawData)
{
TypeCode parameterTypeCode = Type.GetTypeCode(item.Value.GetType());
var transformationFactory = transformationFactoryProvider.ContainsKey(parameterTypeCode)
? transformationFactoryProvider[parameterTypeCode]
: defaultFactory;
var transformedItem = transformationFactory(item.Value);
XmlElement xmlElement = doc.CreateElement("pr");
xmlElement.SetAttribute("tp", transformedItem.Item1);
xmlElement.SetAttribute("nm", item.Key);
xmlElement.SetAttribute("vl", transformedItem.Item2);
doc.FirstChild.NextSibling.AppendChild(xmlElement);
}
}
return doc.OuterXml;
}
使用示例:
// Transformation Factories
// Input: raw object
// Output: Item1: type name, Item2: value in the finally formatted string
Func<object, Tuple<string, string>> numericFactory = raw => Tuple.Create("int", raw.ToString());
Func<object, Tuple<string, string>> dateTimeFactory =
raw => Tuple.Create("datetime", (raw as DateTime?).GetValueOrDefault().ToString("o"));
// Transformation Factory Provider
// Input: TypeCode
// Output: transformation factory for the given type
var transformationFactoryProvider =
new Dictionary<TypeCode, Func<object, Tuple<string, string>>>
{
{TypeCode.Int16, numericFactory},
{TypeCode.Int32, numericFactory},
{TypeCode.Int64, numericFactory},
{TypeCode.DateTime, dateTimeFactory}
};
// Convert to XML given parameters
IDictionary<string, object> parameters = new Dictionary<string, object>
{
{ "SOMEDATA", 12 },
{ "INTXX", 23 },
{ "DTTM", DateTime.Now },
{ "PLAINTEXT", "Plain Text" },
{ "RAWOBJECT", new object() },
};
string xmlParameters = this.ConvertToXml(parameters, transformationFactoryProvider);