XMLDescendants to Object

本文关键字:Object to XMLDescendants | 更新日期: 2023-09-27 18:14:13

我正在解析XML以创建对象。我只是不确定如何将var lotConfig转换为lotConfig对象。

I have try:

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

return lotConfig as LotConfig

但是到目前为止都没有成功。

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

XMLDescendants to Object

目前lotConfigIEnumerable<LotConfig>类型,您需要在LINQ结束时调用.FirstOrDefault()以使其返回单个LotConfig类型:

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