Search code examples
c#xmlcastingxelement

XMLDescendants to Object


I am parsing XML to create an object. I am just unsure as to how to cast the var lotConfig into a LotCOnfig object.

I have tried :

var lotConfig =  (LotConfig) xml.Descendants("LOT_CONFIGURATON").Select(

and

return lotConfig as LotConfig

But None have worked so far.

 public LotConfig GetLotConfigData(FileInfo lotFile)
        {
            var xml = XElement.Load(lotFile.FullName);

            var lotConfig =  xml.Descendants("LOT_CONFIGURATON").Select(
                lot => new LotConfig
                {
                    LotNumber = (string) lot.Element("LOT_NUMBER").Value,
                    LotPartDescription = lot.Element("PART_DESCRIPTION").Value,
                    LotDate = lot.Element("LOT_DATE").Value,

                    ComponentList = lot.Descendants("ASSY_COMPONENT").Select(ac => new LotComponent
                       {
                           PartNumber = ac.Descendants("COMPONENT_PART_NUMBER").FirstOrDefault().Value,
                           ArtworkNumber = ac.Descendants("ARTWORK_NUMBER").FirstOrDefault().Value,
                           RefDesignator = ac.Descendants("REFERENCE_DESIGNATOR").FirstOrDefault().Value
                       }).ToList()
                });


            return lotConfig as LotConfig;
        }

Solution

  • Currently lotConfig is of type IEnumerable<LotConfig>, you need to call .FirstOrDefault() at the end of your LINQ to make it return single LotConfig type :

    var lotConfig =  xml.Descendants("LOT_CONFIGURATON")
                        .Select(
                            lot => new LotConfig
                            {
                                LotNumber = (string) lot.Element("LOT_NUMBER").Value,
                                LotPartDescription = lot.Element("PART_DESCRIPTION").Value,
                                LotDate = lot.Element("LOT_DATE").Value,
    
                                ComponentList = lot.Descendants("ASSY_COMPONENT").Select(ac => new LotComponent
                                   {
                                       PartNumber = ac.Descendants("COMPONENT_PART_NUMBER").FirstOrDefault().Value,
                                       ArtworkNumber = ac.Descendants("ARTWORK_NUMBER").FirstOrDefault().Value,
                                       RefDesignator = ac.Descendants("REFERENCE_DESIGNATOR").FirstOrDefault().Value
                                   }).ToList()
                            })
                        .FirstOrDefault();