Deserialize XML into Dictionary<string, string>

谁说胖子不能爱 提交于 2020-01-02 04:42:11

问题


I have some XML;

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

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.

EDIT: 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?


回答1:


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)

UPDATE: As OP said in his edit, if there's no way to use Linq-to-Xml, then you¡ll need to customize XML serialization implementing IXmlSerializable (you might want to check this other Q&A: custom xml serialization ).




回答2:


You can use LINQ to XML with method ToDictionary();



来源:https://stackoverflow.com/questions/9210059/deserialize-xml-into-dictionarystring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!