开发者

Improving Linq-XML to Object query

I want to use Linq to extract data from an XML document and place it into a list

<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开发者_Go百科</Wind>
        <Flaps>5</Flaps>
        <Switches></Switches>
        <Runways>
            <Rwy>6L</Rwy>
            <Rwy>6R</Rwy>
        </Runways>
        ...
     </TLDRequest>
    ...
  </FlightData>
</Data>

My Linq code in C# works - I can get attributes from the FlightData tab, but I think it could be more efficient, especially in the area of getting data from the TLDRequest tag. Can I get some insight on using best practices to get to and grab child tags?

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

Best regards


Your query is fine, generally speaking. If you want to cut down on some of the redundancy, consider using let to get the TLDRequest element once, so you repeat yourself a bit less.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜