我需要创建一个具有动态命名属性的对象:
<users>
<user1name>john</user1name>
<user2name>max</user2name>
<user3name>asdf</user3name>
</users>
这可能吗?
答案 0 :(得分:4)
是的,绝对的。只需将其用作IDictionary<string, object>
填充:
IDictionary<string, object> expando = new ExpandoObject();
expando["foo"] = "bar";
dynamic d = expando;
Console.WriteLine(d.foo); // bar
在您的XML情况下,您可以遍历元素,例如
var doc = XDocument.Load(file);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var element in doc.Root.Elements())
{
expando[element.Name.LocalName] = (string) element;
}