问题描述
我有一些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到字典<字符串,字符串>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!