如何将对象集合/字典序列化为<key> value </ key>

mwj*_*son 13 .net c# xml serialization xml-serialization

有没有办法将键/值对(最好是强类型,但也可能来自词典)序列化为下面所需的格式?

public List<Identifier> Identifiers = new List<Identifiers>();

public class Identifier
{
    public string Name { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这通常序列化为以下内容:

<Identifiers>
  <Identifier>
    <Name>somename</Name>
    <Description>somedescription</Description>
  </Identifier>
  <Identifier>
    ...
  </Identifier>
</Identifiers>
Run Code Online (Sandbox Code Playgroud)

我们考虑的另一种可能的方法是使用哈希表/字典:

public Dictionary<string, string> Identifiers = new Dictionary<string,string>
{
    { "somename", "somedescription"},
    { "anothername", "anotherdescription" }
};
Run Code Online (Sandbox Code Playgroud)

但这将要求自定义序列化词典或自定义XmlWriter.

我们想要实现的输出是:

<Identifiers>
  <somename>somedescription</somename>
  <anothername>anotherdescription</anothername>
</Identifiers>
Run Code Online (Sandbox Code Playgroud)

因此,我们正在寻找代码示例,以了解如何以最佳方式获取我们想要的输出.

编辑:也许我应该更好地解释.我们已经知道如何序列化对象.我们正在寻找的是特定类型的序列化的答案......我将扩展上面的问题

L.B*_*L.B 22

使用LINQ to XML很容易:

Dictionary<string, string> Identifiers = new Dictionary<string,string>()
{
    { "somename", "somedescription"},
    { "anothername", "anotherdescription" }
};

XElement xElem = new XElement("Identifiers",
                               Identifiers.Select(x=>new XElement(x.Key,x.Value)));

string xml = xElem.ToString(); //xElem.Save(.....);
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

<Identifiers>
  <somename>somedescription</somename>
  <anothername>anotherdescription</anothername>
</Identifiers>
Run Code Online (Sandbox Code Playgroud)


Kei*_*ith 7

这很难回答,因为您没有真正阐明"最佳"对您意味着什么.

最快的可能是原始的字符串:

var sb = new StringBuilder();
sb.Append("<identifiers>");
foreach(var pair in identifiers)
{
    sb.AppendFormat("<{0}>{1}</{0}>", pair.Key, pair.Value);
}
sb.Append("</identifiers>");
Run Code Online (Sandbox Code Playgroud)

显然,没有处理任何转义为XML,但那可能不是一个问题,它完全取决于你的字典的内容.

最少的代码行怎么样?如果那是你的要求,那么LB的Linq to XML答案可能是最好的.

内存占用量最小的是什么?在那里,我会考虑删除Dictionary并创建自己的可序列化类,它会丢弃哈希开销和集合功能,而只是存储名称和值.那可能也是最快的.

如果您的要求代码简单,那么如何使用dynamic或匿名类型而不是Dictionary

var anonType = new
{ 
    somename = "somedescription",
    anothername = "anotherdescription" 
}

// Strongly typed at compile time
anonType.anothername = "new value";
Run Code Online (Sandbox Code Playgroud)

这样你就不会处理集合中属性名称的"魔术字符串" - 它会在你的代码中强烈输入(如果这对你很重要).

但是匿名类型不具有一个内置串行器-你必须写一些东西给自己,使用的一个许多 开放 源码 的替代品,甚至使用XmlMediaTypeFormatter.

负载的方法可以做到这一点,哪一个是最好的取决于你打算如何使用它.