2010-04-08 74 views
3

我有一个程序需要将特定标记的两个属性转换为Dictionary<int,string>的键和值。该XML看起来是这样的:将XML属性转换为Linq中的字典到XML

(片段)

<startingPoint coordinates="1,1" player="1" /> 

,到目前为止,我的LINQ看起来是这样的:

XNamespace ns = "http://the_namespace"; 
var startingpoints = from sp in xml.Elements(ns+"startingPoint") 
       from el in sp.Attributes() 
       select el.Value; 

它得到了我一个很好IEnumerable装满了东西,如“1, 1“和”1“,但是应该有一种方法来适应像this answer这样的属性来代替元素。请帮忙吗?谢谢!

+0

应该得到的解释是什么样的?玩家作为键和他们的坐标值? – 2010-04-08 17:11:49

+0

是的,确切地说。这将通过一个getter传递出去,调用函数可以解析它,但是它需要。 – NateD 2010-04-08 18:21:58

回答

3

我假设你想存储所有玩家及其各自的起点坐标在字典中的映射。该代码,这看起来像:

Dictionary<int, string> startingpoints = xml.Elements(ns + "startingPoint") 
     .Select(sp => new { 
           Player = (int)(sp.Attribute("player")), 
           Coordinates = (string)(sp.Attribute("coordinates")) 
          }) 
     .ToDictionary(sp => sp.Player, sp => sp.Coordinates); 

更妙的是,你有一类用于存储的坐标,如:

class Coordinate{ 
    public int X { get; set; } 
    public int Y { get; set; } 

    public Coordinate(int x, int y){ 
     X = x; 
     Y = y; 
    } 

    public static FromString(string coord){ 
     try 
     { 
      // Parse comma delimited integers 
      int[] coords = coord.Split(',').Select(x => int.Parse(x.Trim())).ToArray(); 
      return new Coordinate(coords[0], coords[1]); 
     } 
     catch 
     { 
      // Some defined default value, if the format was incorrect 
      return new Coordinate(0, 0); 
     } 
    } 
} 

然后,你可以解析字符串为坐标马上:

Dictionary<int, string> startingpoints = xml.Elements(ns + "startingPoint") 
     .Select(sp => new { 
           Player = (int)(sp.Attribute("player")), 
           Coordinates = Coordinate.FromString((string)(sp.Attribute("coordinates"))) 
          }) 
     .ToDictionary(sp => sp.Player, sp => sp.Coordinates); 

然后,您可以访问玩家坐标如下:

Console.WriteLine(string.Format("Player 1: X = {0}, Y = {1}", 
           startingpoints[1].X, 
           startingpoints[1].Y)); 
0

我想你希望做这样的事情

string xml = @"<root> 
       <startingPoint coordinates=""1,1"" player=""1"" /> 
       <startingPoint coordinates=""2,2"" player=""2"" /> 
       </root>"; 

XDocument document = XDocument.Parse(xml); 

var query = (from startingPoint in document.Descendants("startingPoint") 
      select new 
      { 
       Key = (int)startingPoint.Attribute("player"), 
       Value = (string)startingPoint.Attribute("coordinates") 
      }).ToDictionary(pair => pair.Key, pair => pair.Value); 

foreach (KeyValuePair<int, string> pair in query) 
{ 
    Console.WriteLine("{0}\t{1}", pair.Key, pair.Value); 
}