反序列化XML到字典<字符串,字符串> [英] Deserialize XML into Dictionary<string, string>

查看:345
本文介绍了反序列化XML到字典<字符串,字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些XML;

<data>
  <name1>James</name1>
  <name2>John</name2>
  etc..
</data>



1,名称2等可以是任何东西,我希望能够得到这个XML转换为字典理想情况下,这是可能的使用内置的.NET序列化?

The name1, name2, etc could be anything, i want to be able to get this xml into a dictionary ideally, is this possible using the built in .net serialisation?

谢谢,
詹姆斯。

Thanks, James.

编辑:理想情况下,我不想使用LINQ。是否有可能连载整个元素数组为字符串?所以我结束了一个字符串对象数据包含所有子元素标记和数据?

Ideally i dont want to use linq. Is it possible to serialise the whole element array to a string? So i'd end up with a string object 'Data' that contained all the child element tags and data?

推荐答案

没有,但是你可以使用的 LINQ到XML 的这样做的:

No, but you can use Linq-to-Xml to do so:

XDocument.Load([file path, stream, whatever]).Descendants("data").Descendants()
    .ToDictionary(element => element.Name, element => element.Value)

更新:
作为OP在他的编辑说,如果有使用没有办法的LINQ到XML ,那么你需要自定义XML序列化实施的IXmlSerializable。

UPDATE: As OP said in his edit, if there's no way using Linq-to-Xml, then you need to customize XML serialization implementing IXmlSerializable.

最后,如果你走这条路,看看这个其他问题

Finally, if you go this way, check this other question.

这篇关于反序列化XML到字典&LT;字符串,字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆