2010-04-08 5 views
3

특정 태그의 두 속성을 Dictionary<int,string>의 키와 값으로 변환해야하는 프로그램이 있습니다. 는 XML은 다음과 같습니다Linq에서 XML로 XML 속성을 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; 

나에게 1 "과 같은 것들로 가득 찬 멋진 IEnumerable를 가져, 1 "과"1 "이지만 요소 대신 속성을 수행하려면 this answer과 같은 것을 적용하는 방법이 있어야합니다. 좀 도와주세요? 고맙습니다!

+0

같은 뭔가를 찾고 생각? 열쇠로서의 플레이어와 값으로서의 좌표? –

+0

네, 그렇습니다. 이것은 getter를 통해 전달 될 것이고 호출하는 함수는 원하는대로 분석 할 수 있습니다. – NateD

답변

3

모든 플레이어와 해당 시작점 좌표의 매핑을 사전에 저장한다고 가정합니다.

: 그럼 당신은 바로 좌표에 문자열을 구문 분석 할 수

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 = (string)(sp.Attribute("coordinates")) 
          }) 
     .ToDictionary(sp => sp.Player, sp => sp.Coordinates); 

더 나은, 당신은 같은 좌표를 저장하는 클래스를했다 : 같은이 코드는 보일 것이다

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