如何将XML转换为Dictionary
我的xml如下:
Log In Password
我没有Linq就成功了,任何人都可以帮我将以下代码转换为Linq:
using (XmlReader reader = XmlReader.Create(_xml)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data") { reader.MoveToAttribute("name"); string key = reader.Value; reader.MoveToContent(); string value = reader.ReadElementContentAsString(); _dictionary.Add(key, value); } } reader.Close(); }
var xdoc = XDocument.Load(path_to_xml); _dictionary = xdoc.Descendants("data") .ToDictionary(d => (string)d.Attribute("name"), d => (string)d);
XDocument xdoc = XDocument.Load("test.XML"); var query = xdoc.Descendants("root") .Elements() .ToDictionary(r => r.Attribute("name").Value, r => r.Value);
记得包括:
using System.Linq; using System.Xml.Linq;
这是一个老问题,但是如果有人遇到'Typed'
(例如来自Android应用程序的SharedPreference
文件),你可以按如下方式处理它:这是我从Instagram
应用程序中获取的这样一个xml的示例。
请注意value属性的不一致性。 某些字段(例如string
类型)没有明确定义它。
var elements = XElement.Load(filePath) .Elements() .ToList(); var dict = new Dictionary(); var _dict = elements.ToDictionary(key => key.Attribute("name").Value, val => val.Attribute("value") != null ? val.Attribute("value").Value : val.Value);