C#XML数据转换成字典

美好的一天,

我一直在使用ToDicationary()扩展方法

var document = XDocument.Load(@"..\..\Info.xml"); XNamespace ns = "http://www.someurl.org/schemas"; var myData = document.Descendants(ns + "AlbumDetails").ToDictionary ( e => e.Name.LocalName.ToString(), e => e.Value ); Console.WriteLine("Writing music..."); foreach (KeyValuePair kvp in myData) { Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value); } 

使用以下XML数据:

     Ottmar Liebert Barcelona Nights Spain    

而且我没有得到我想要的输出。 相反,我得到了这个:

 Writing music... AlbumDetails = Ottmar LiebertBarcelona NightsSpain 

相反,我想要myData(“艺术家”)=“Ottmar Liebert”等…

是否有可能与后代?

TIA,

COSON

以下将只获取AlbumDetails节点:

 document.Descendants(ns + "AlbumDetails") 

你想要它的直接后代(子节点) – 因为它们也是元素:

 document.Descendants(ns + "AlbumDetails").Elements() 

整行将是:

 var myData = document.Descendants(ns + "AlbumDetails") .Elements().ToDictionary( e => e.Name.LocalName.ToString(), e => e.Value ); 

试试这个。

 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); }