将XML属性转换为Linq中的Dictionary到XML

时间:2010-04-08 16:59:43

标签: c# linq-to-xml

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

(片段)

<int,string>

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

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

这给了我一个很好的XNamespace ns = "http://the_namespace"; var startingpoints = from sp in xml.Elements(ns+"startingPoint") from el in sp.Attributes() select el.Value; 充满了像“1,1”和“1”这样的东西,但是应该有一种方法来调整像this answer这样的东西来做属性而不是元素。请帮忙吗?谢谢!

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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);
}