[英]Linq multiple select by xml attributes
我想根據元素的屬性從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.Element(ns+"Cube").Attribute("currency").Value
,所以我希望能夠檢查所有多維數據集的Elements: cube.Elements(ns+"Cube").Attributes("currency").Values
(復數),但不可能這樣。 知道如何制作多個物體嗎? 我的名稱中有3個字符串,因此在這里我需要3個不同的對象。 自第一個對象以來,它僅適用於USD。
我的最終結果應該是X列表,每個列表包含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")
};
});
});
這對我來說很好。 但是請注意,您鏈接的XML中沒有使用“ ROM”或“ SMT”作為貨幣的元素。 “ RON”似乎是有效的(因此我已經相應地更新了名稱數組),但看不到“ 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")
select
(
from innercube in cube.Elements(ns+"Cube")
where names.Contains((string)innercube.Attribute("currency"))
select (object)new
{
datum = (DateTime)cube.Attribute("time"),
currency = (string)innercube.Attribute("currency"),
rate = (string)innercube.Attribute("rate")
}
).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.