在Linq to XML中将XML属性转换为字典

3
我有一个程序需要将特定标记的两个属性转换为Dictionary<int, string>的键和值。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"这样的东西,但应该有一种方法可以调整类似此答案以执行属性而不是元素。能帮忙一下吗?谢谢!

生成的字典应该长什么样子?玩家作为键,他们的坐标作为值? - Philip Daubmeier
没错。这将通过getter传递出去,调用函数可以按其意愿解析它。 - NateD
2个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接