我想使用Linq从XML文档中提取数据并将其放入列表
<Data>
<FlightData DTS="20110216 17:17" flight="1234" origin="CYYZ" dest="CYUL" aircraft="945">
<TLDRequest>
<Airline>ABC</Airline>
<AcReg>C-FABC</AcReg>
<CalcType>T</CalcType>
<OAT>-05</OAT>
<Wind>060/10</Wind>
<Flaps>5</Flaps>
<Switches></Switches>
<Runways>
<Rwy>6L</Rwy>
<Rwy>6R</Rwy>
</Runways>
...
</TLDRequest>
...
</FlightData>
</Data>
我在C#中的Linq代码工作 - 我可以从FlightData选项卡获取属性,但我认为它可能更有效,特别是在从TLDRequest标记获取数据的领域。我是否可以通过最佳实践来获取和获取子标签?
public static List<ACARS_Phase> createAcarsPhaseObject(XDocument xDoc)
{
return (from ao in xDoc.Descendants("FlightData")
select new ACARS_Phase
{
FlightDate = DateTime.ParseExact(ao.Attribute("DTS").Value, "yyyyMMdd HH:mm", new CultureInfo("en-CA")),
FlightNumber = ao.Attribute("flight").Value,
Origin = ao.Attribute("origin").Value,
Destination = ao.Attribute("dest").Value,
InternalFinNumber = ao.Attribute("aircraft").Value,
OperatorCode = ao.Element("TLDRequest").Element("Airline").Value,
RegistrationNumber = ao.Element("TLDRequest").Element("AcReg").Value,
Wind = ao.Element("TLDRequest").Element("Wind").Value,
Flaps = ao.Element("TLDRequest").Element("Flaps").Value,
OAT = ao.Element("TLDRequest").Element("OAT").Value,
}).ToList();
}
祝你好运
答案 0 :(得分:3)
一般来说,你的查询很好。如果你想减少一些冗余,可以考虑使用let
一次获取TLDRequest元素,这样你就可以重复一点。
return (from ao in xDoc.Descendants("FlightData")
let request = ao.Element("TLDRequest")
select new AcARS_Phase
{
// stuff
OperatorCode = request.Element("Airline").Value,
RegistrationNumber = request.Element("AcReg").Value,
// etc.
}).ToList();