[英]Reading XML values from different namespaces in same LINQ Query
我希望你們能夠幫助我嗎?
我有這個XML結構:
<DataBase
xsi:schemaLocation="http://somestuff.new/xml http://somestuff.xsd"
xmlns:ns3="http://somestuff.new/ns3"
xmlns:ns2="http://somestuff.new/ns2"
xmlns="http://somestuff.new/ns"
xmlns:xsi="http://somestuff.new/XMLScema-instance"
xmlns:ns4="http://somestuff.new/ns4">
<Cars>
<SmallCars attribute="Something">
<Id>licenceplate</Id>
<Parts attribute="All Parts">
<Extras>
<Gauges xmlns="http://somestuff.new/ns3">
<Speed>100</Speed>
<Rpm>3200</Rpm>
</Gauges>
</Extras>
</Parts>
</SmallCars>
</Cars>
</DataBase>
然后,我創建了這樣的汽車類:
public class Cars
{
public string CarType { get; set; }
public List<Parts> CarParts { get; set; }
}
和一類零件:
public class Parts
{
public List<Gauges> CarExtras { get; set; }
}
最后但並非最不重要的一類儀表:
public class Gauges
{
public double Speed { get; set; }
public int Rpm { get; set; }
}
現在,我想創建一個LINQ查詢,該查詢從XML的Gauges部分獲取值,但是我的嘗試似乎失敗了:
XDocument xml = XDocument.Load(file);
XNamespace xmlns =XNamespace.Get("http://somestuff.new/ns");
XNamespace ns3 = XNamespace.Get("http://somestuff.new/ns3");
var Cars = from car in xml.Descendants(ns + "Cars")
select new Cars
{
CarParts = (from part in car.Descendants(ns + "Parts")
select new Parts
{
CarExtras = (from extra in part.Descendants(ns + "Extras")
select new Gauges
{
Speed = (double?)extra.Element(ns3 + "Speed") ?? 0.0,
Rpm = (int?)extra.Element(ns3 + "Rpm") ?? 0
})
})
});
我嘗試了很多與名稱空間的組合,因為當我到達Gauges時它會更改,但是沒有返回任何值。
希望有人可以在這里幫助我嗎?
請注意, extra
,在你的LINQ到XML代碼<Extras>
元素,因為<Speed>
和<Rpm>
是不是直接子<Extras>
你無法使用選擇其中任何extra.Element(ns3 + "elementName")
。 在這種情況下,可以使用Descendants
代替Element
:
XNamespace ns =XNamespace.Get("http://somestuff.new/ns");
XNamespace ns3 = XNamespace.Get("http://somestuff.new/ns3");
var Cars = from car in xml.Descendants(ns + "Cars")
select new Cars
{
CarParts = (from part in car.Descendants(ns + "Parts")
select new Parts
{
CarExtras =
(from extra in part.Descendants(ns + "Extras")
select new Gauges
{
Speed =
(double?)
extra.Descendants(ns3 + "Speed").FirstOrDefault() ??
0.0,
Rpm =
(int?)
extra.Descendants(ns3 + "Rpm").FirstOrDefault() ?? 0
}).ToList()
}).ToList()
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.