Linq通过xml属性进行多重选择

时间:2015-07-04 01:04:46

标签: c# xml linq

我想选择多个" new"来自xml文件的对象基于元素的属性: 例如:

XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
var names = new[] { "USD", "ROM", "SMT" };
var Cubes = from cube in XDocument.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml").Root.Element(ns + "Cube").Elements(ns + "Cube")
                            where names.Contains(cube.Element(ns + "Cube").Attribute("currency").Value)
                            select new List<object>
                            {
                                new
                                {
                                datum = (DateTime)cube.Attribute("time"),
                                currency = (string)cube.Element(ns + "Cube").Attribute("currency"),
                                rate = (string)cube.Element(ns + "Cube").Attribute("rate")
                                }

                            };

这里的问题是我只能通过以下方式选择第一个元素: cube.Element(ns+"Cube").Attribute("currency").Value,所以我希望能够检查所有多维数据集的元素: cube.Elements(ns+"Cube").Attributes("currency").Values(复数)但不可能这样。知道如何制作多个对象吗?我在名字中有3个字符串,所以我需要3个不同的对象。它仅适用于USD,因为它是第一个对象。

我的最终结果应该是X个列表,每个列表包含3个对象。

2 个答案:

答案 0 :(得分:3)

XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
var xdoc = XDocument.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml");
var names = new[] { "USD", "RON", "SMT" };
var someCubes =  xdoc.Root.Element(ns + "Cube")
    .Elements()
    .Select(x => x.Elements()
    .Where(y => names.Contains(y.Attribute("currency").Value)))
    .Select(x => {
        return x.Select(y => {
            return new {
                datum = (DateTime)y.Parent.Attribute("time"),
                currency = (string)y.Attribute("currency"),
                rate = (string)y.Attribute("rate")
            };
        });
    });

enter image description here

这对我来说很好。但请注意,您链接的XML中没有“ROM”或“SMT”作为货币的元素。 “RON”似乎是一个有效的(所以我相应更新了名称数组),但我没有看到“SMT”。

答案 1 :(得分:3)

使用更多查询语法的另一种选择:

ng-disabled