2011-12-13 64 views
0

这里是XML我有一个文件:我如何将XML到词典列表用C#在Windows Phone 7

特别注意: 这是Windows Phone 7的,不是一般的C#问题

<?xml version="1.0" encoding="UTF-8"?> 
<rss version="2.0"> 
    <item> 
     <date>01/01</date> 
     <word>aberrant</word> 
     <def>straying from the right or normal way</def> 
    </item> 

    <item> 
     <date>01/02</date> 
     <word>Zeitgeist</word> 
     <def>the spirit of the time.</def> 
    </item> 
</rss> 

我需要它在Dictionary对象的List(又名数组)。每个Dictionary代表<item>。像<word>这样的每个元素是key,其类型为string,每个值像“Zeitgeist”是value,其类型为string

有没有简单的方法来做到这一点?我来自Objective-C和iOS,所以这对于.NET和C#来说是全新的。

回答

2

LINQ-to-XML使它变得非常简单。这里有一个完整的例子:

 public static void Main(string[] args) 
     { 
      string xml = @" 
<rss version='2.0'> 
    <item> 
     <date>01/01</date> 
     <word>aberrant</word> 
     <def>straying from the right or normal way</def> 
    </item> 

    <item> 
     <date>01/02</date> 
     <word>Zeitgeist</word> 
     <def>the spirit of the time.</def> 
    </item> 
</rss>"; 
      var xdoc = XDocument.Parse(xml); 
      var result = xdoc.Root.Elements("item") 
       .Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value)) 
       .ToList(); 

     } 

而是从XDocument.Parse()的字符串装载的,你可能会做XDocument.Load(文件名),但你得到一个XDocument对象一起工作无论哪种方式(我做了字符串只是例如)。

1

您可以使用LINQ的XML做到这一点:

var doc = XDocument.Parse(xml); //xml is a String with your XML in it. 
doc 
.Root       //Elements under the root element. 
.Elements("item")    //Select the elements called "item". 
.Select(      //Projecting each item element to something new. 
    item =>     //Selecting each element in the item. 
     item     //And creating a new dictionary using the element name 
     .Elements()   // as the key and element value as the value. 
     .ToDictionary(xe => xe.Name.LocalName, xe => xe.Value)) 
.ToList(); 
+0

如何将Linq添加到我的项目中?使用System.Xml.Linq添加给我一个错误,说它不在程序集中。谢谢您的帮助。 – 2011-12-13 22:46:02