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

发布于 2024-08-28 07:54:44 字数 644 浏览 4 评论 0原文

我有一个程序需要将特定标记的两个属性转换为 Dictionary 的键和值。 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”之类的内容,但应该有一种适应这个答案之类的方法来处理属性而不是元素的方法。请帮忙一点?谢谢你!

I've got a program that needs to convert two attributes of a particular tag to the key and value of an Dictionary<int,string>. The XML looks like this:

(fragment)

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

and so far my LINQ looks something like this:

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

Which gets me a nice IEnumerable full of things like "1,1" and "1", but there should be a way to adapt something like this answer to do attributes instead of elements. Little help please? Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

此岸叶落 2024-09-04 07:54:44

我假设您想在字典中存储所有玩家的映射及其各自的起点坐标。代码如下所示:

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

I assume you want to store a mapping of all players and their respective starting point coordinates in the dictionary. The code for this would look like:

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

Even better, you had a class for storing the coordinates, like:

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

Then you could parse the string into coordinates right away:

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

You could then access the players coordinates like this:

Console.WriteLine(string.Format("Player 1: X = {0}, Y = {1}", 
                                startingpoints[1].X, 
                                startingpoints[1].Y));
傲世九天 2024-09-04 07:54:44

我想你想做这样的事情

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

I think you're looking to do something like this

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文