将XML文档转换为字典

我不需要编辑任何XML文件或任何东西,这只是用于阅读和解析。

我希望能够将XML文档作为字典处理,例如: username = doc["username"]; ,但我无法找到如何“转换”文件。 我也遇到了重复键名的问题,但通过将每个值附加为1,2等可以很容易地避免这种情况。 也很容易循环。

这可能吗? 将(已解析的)XML文档视为字典?


对Mehrdad的回答:它有时会有所不同,这取决于用户的要求。 如果用户请求x ,那么它将是:

  foo 123 foobar  

但如果他要求y ,那就像

  1000 ...@... foobar  

最好的是这样:

  100 3 foo bar bar " 

可以解析,然后以doc["mengde"]等方式进行访问。

你可以使用linq到xml做你想要的(如果我明白你想要的)

 string data = "foofoobbbbb123foobar"; XDocument doc = XDocument.Parse(data); Dictionary dataDictionary = new Dictionary(); foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false)) { int keyInt = 0; string keyName = element.Name.LocalName; while (dataDictionary.ContainsKey(keyName)) { keyName = element.Name.LocalName + "_" + keyInt++; } dataDictionary.Add(keyName, element.Value); } 

XML数据

   foo bar bar  

转换代码

 string s = "foobarbar"; XmlDocument xml = new XmlDocument(); xml.LoadXml(s); XmlNodeList resources = xml.SelectNodes("data/resource"); SortedDictionary dictionary = new SortedDictionary(); foreach (XmlNode node in resources){ dictionary.Add(node.Attributes["key"].Value, node.InnerText); } 

这个问题在此之前被问过,因此您可以在此链接中找到所有答案:

将xml转换为已排序的字典

希望能帮助到你。

你的问题真的不太清楚,但我认为这可以做你想要的:

 XmlDocument doc = new XmlDocument(); doc.LoadXml(@" 100 2 bar "); Dictionary d = new Dictionary(); foreach (XmlNode n in doc.SelectNodes("/xml/*") { d[n.Name] = n.Value; } 

这不是您正在寻找的,但可能有趣: http : //blogs.msdn.com/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the -expandoobject.aspx

还有比这个烂摊子更简单的方法吗? 这也是因为我只能检测到孩子的孩子。

 string s = @"  100 2 bar "; XmlDocument xml = new XmlDocument(); xml.LoadXml(s); SortedDictionary dictionary = new SortedDictionary(); foreach (XmlNode node in xml) { if (node.NodeType == XmlNodeType.Element && node.HasChildNodes) { foreach (XmlNode node2 in node) { if (node2.NodeType == XmlNodeType.Element && node2.HasChildNodes) { foreach (XmlNode node3 in node2) { if (node3.NodeType == XmlNodeType.Element && node3.HasChildNodes) { foreach (XmlNode node4 in node3) { if (node4.NodeType == XmlNodeType.Element && node4.HasChildNodes) { foreach (XmlNode node5 in node4) { dictionary.Add(node5.ParentNode.Name, node5.InnerText); } } else { dictionary.Add(node4.ParentNode.Name, node4.InnerText); } } } else { dictionary.Add(node3.ParentNode.Name, node3.InnerText); } } } else { dictionary.Add(node2.Name, node2.InnerText); } } } else { dictionary.Add(node.Name, node.InnerText); } }